﻿var funcs = [];
var randomData = [];
var eventHandlers = [];

var layer;


if (!window.WebUIJS) {
    window.WebUIJS = {};
}



/**
 * 将data中的数据,根据config参数的配置填充到控件中,一般是配合ShowDataPicker函数在回调时使用,如果data是数组,则填充的值以逗号分隔
 * 函数会自动判断是input元素还是其他元素,input使用$().val()填充 ,其他元素使用 $().text()填充
 * @param {json} data 用于填充元素的数据
 * @param {json} config 用于指定配置的参数,格式为 {'筛选器':'data中的字段名'}
 * @returns {} 无
 */
WebUIJS.FillDataToControl = function (data, config) {
    if (!isObject(data)) {
        console.log("传入的data不是ojbect或者array");
        return;
    }

    //if (isArray(data)) {
    //    data = data[0];
    //}

    for (var p in config) {
        var ctrlID = p;
        var propName = config[p];
        var newValue = "";

        var valueStr = "";

        if (isArray(data)) {
            for (var i = 0; i < data.length; i++) {
                var tmp = data[i];

                if (tmp.hasOwnProperty(propName)) {
                    newValue += (tmp[propName]);
                    newValue += ','
                }
            }

            newValue = newValue.slice(0, -1);
        } else {
            if (data.hasOwnProperty(propName)) {
                newValue = data[propName];
            }
        }

        if ($(ctrlID).is('input')) {
            $(ctrlID).val(newValue);
        } else {
            $(ctrlID).text(newValue);
        }
    }
}

WebUIJS.SetElementValue = function(element, value) {
    if ($(element).is('input')) {
        $(element).val(value);
    } else {
        $(element).text(value);
    }
}


/**
 * 该函数用于在列表页中的各行的操作提交
 * @param {dom} sender 调用者(提交时会锁定)
 * @param {string} url 提交数据的Url
 * @param {string} methodName 函数名
 * @param {json} data 提交的数据
 * @param {string} tipMessage 是否需要弹出提示框
 * @returns {} 
 */
WebUIJS.AjaxToMethod = function (sender, url, methodName, data, tipMessage) {
    if ($(sender).attr('disabled') != null) {
        return;
    }

    if (!url || isEmpty(url)) {
        url = $(sender).data("url");
    }

    if (methodName == undefined) {
        methodName = $(sender).data("cmd");
    }

    if (!data) {
        data = $(sender).data("args");
    }

    if (!tipMessage || tipmessage=="") {
        tipMessage = $(sender).data("tips");
    }

    if (!isEmpty(tipMessage)) {
        if (!confirm(tipMessage)) {
            return;
        }
    }

    if (sender != null && $(sender).is("button")) {
        //$(sender).ladda('start');
        $(sender).attr("disabled", "disabled");
    }

    $(sender).data('disabled', 'disabled');
    
    if (data == null) {
        data = {
            MethodName: methodName,
            cmdName: methodName
        }
    } else {
        data.MethodName = methodName;
        data.cmdName = methodName;
        
    }

    var autoRefresh = $(sender).data("autorefresh").toLowerCase() == "true";
    var autoRefreshPage = $(sender).data("autorefreshwholepage").toLowerCase() == "true";
    var successCall = $(sender).data("aftersuccesscall");
    

    //var index = layer.load();
    $.ajax(url, {
        async: true,
        cache: false,
        type: "POST",
        data: data,
        dataType: "json",
        beforeSend: function () {
            WebUIJS.Loading();
        },
        success: function (result, status, xhr) {
            if (result == null) {
                return;
            }

            if (result.IsSuccess === true) {
                var msg = "";

                if (result.Message === "" || result.Message == null) {
                    msg="操作已成功";
                } else {
                    msg=result.Message;
                }

                WebUIJS.Alert(msg,
                    function() {
                        if (typeof (successCall) != "undefined") {
                            __callBackFuncOrStr(successCall, sender, [result]);
                        }

                        if (autoRefreshPage) {
                            WebUIJS.Refresh();
                            return;
                        }

                        if (autoRefresh) {
                            WebUIJS.Refresh(sender);
                        }
                    });


            } else {
                alert(result.Message);

            }
        },
        error: function (xhr, status, error) {
            if (status === 500) {
                WebUIJS.Alert("服务器返回500内部错误,请查看网络请求");
            } else {
                WebUIJS.Alert("调用出错:" + error);
            }
        },
        complete: function (xhr, status) {

            $(sender).attr('disabled', null);
            WebUIJS.CloseLoading();
        }
    });

    //$.getJSON(url, data, function (result, status, xhr) {


    //    //layer.closeAll('loading');

    //    //if (status==404) {

    //    //}

    //    if (result == null) {
    //        return;
    //    }

    //    if (result.IsSuccess === true) {
    //        if (result.Message === "" || result.Message == null) {
    //            alert("操作已成功");
    //        } else {
    //            alert(result.Message);
    //        }


    //        WebUIJS.Refresh(sender);
    //    } else {
    //        alert(result.Message);

    //    }
    //});
}

/**
 * 跳转到指定url,如果sender是弹出窗,则将弹出窗加载为url的内容
 * @param {string} url  跳转的Url
 * @param {} sender 触发该调转的元素,跳转时,会锁定该元素,无法重复触发
 * @returns {} 
 */
WebUIJS.GoTo = function (url, sender,target,isManage) {
    if (!target) {
        target = "_self";
    }

    if (target != "" && target != "_self") {
        var win = window.open(url, target);
        win.focus();
        return;
    }

    if (sender != undefined && sender != null) {
        var closestEl = $(sender).closest(".layui-layer");
        
        if (closestEl.hasClass('layui-layer')) {
            if (closestEl.find(".datapicker").length > 0) {
                return;
            }

            if (closestEl.find(".modalwindow").length > 0) {
                WebUIJS.ModalByUrl(url,null,
                function () {
                    var index = $(closestEl).attr("times");
                    layer.close(index);
                });
            }

        } else {
            window.location.href = url;
        }
    } else {
        window.location.href = url;
    }


}

/**
 * 刷新当前页面
 * @param {} sender 
 * @returns {} 
 */
WebUIJS.Refresh = function (sender) {
    var url = window.location.href;

    if (sender.closest(".modalwindow").length>0) {
        url = sender.closest(".modalwindow").data("action");
    }

    WebUIJS.GoTo(url, sender);
}

/**
 * 提交一个form,如果是内嵌的form,则只提交内嵌form的部分,如果是form,则调用form的提交
 * @param {element} form 用于提交的元素,,必须是form或者div[data-innerform="True"] 元素
 * @param {boolean} forceAjax 是否将form强制使用ajax提交
 * @param {function} onSucessCallback 成功请求时,回调函数 function(html)
 */
WebUIJS.Submit = function (sender, forceAjax, onSucessCallback) {
    sender = $(sender);

    if (sender != null && sender.length > 0) {
        if (sender.is('div[data-innerform="True"]')) {
            if (forceAjax && forceAjax == true) {

            }

            sender.data("submit")();

            return false;
        } else if (sender.is('form:not(.fakeform)')) {
            sender.first().submit();
            return false;
        } else {
            var modal = $(sender).closest(".modalwindow");
            var form;
            if (modal.length > 0) {
                form = modal.find('form:not(.fakeform),div[data-innerform="True"]');
            } else {
                form = $(sender).closest('form:not(.fakeform),div[data-innerform="True"]');
            }

            if (form && form != null && form.length > 0) {

                if (form.is('div[data-innerform="True"]')) {
                    if (forceAjax && forceAjax == true) {

                    }

                    form.data("submit")();

                    return false;
                } else if (form.is('form')) {
                    form.first().submit();
                    return false;
                }
            }

            return false;
        }
    } 
}


/**
 * 弹出一个提示框
 * @param {string} text 提示文本
 * @param {string} onhideCallback 关闭时回调
 */
WebUIJS.Alert = function (text, onhideCallback) {
    layui.layer.alert(text, function (index) {

        layer.close(index);

        if (onhideCallback) {
            onhideCallback();
        }

    });
}

/**
 * 该函数用于弹出一个确认框
 * @param {string} text  弹出框的提示文本
 * @param {string} title 弹出框的标题
 * @param {function} onYes  点击确认的时候回调
 * @param {function} onNo 点击取消的时候回调
 */
WebUIJS.Confirm = function (text, title, onYes, onNo) {
    if (!title) {
        title = "提示";
    }

    layui.layer.confirm(text, {
            icon: 3,
            title: title
        },
        function (index) {
            layer.close(index);
            if (onYes) {
                onYes();
            }
        },
        function (index) {
            layer.close(index);
            if (onNo) {
                onNo();
            }
        });
}

/**
 * 显示一个居中的提示层
 * @param {} text 显示的文本
 * @param {} type 显示的类型:  success,error 二选一
 * @param {} timeout  超时隐藏时间,默认2秒,单位为秒
 * @param {} onHideCallback 隐藏时,回调函数
 * @returns {} 
 */
WebUIJS.Toast = function (text, type, timeout, onHideCallback) {
    var icon = 1;
    if (type == "success") {
        icon = 1;
    } else if (type == "cancel") {
        icon = 2;
    }

    if (!timeout) {
        timeout = 2;
    }

    layui.layer.msg(text, {
        icon: icon,
        time: timeout * 1000 //2秒关闭（如果不配置，默认是3秒）
    }, function () {
        if (onHideCallback) {
            onHideCallback();
        }

    });
}

/**
 * 弹出一个文本输入框获取输入的数据
 * @param {string} title  标题
 * @param {string} defaultValue 默认值
 * @param {function(value)} onYes 点击确定时,回调的函数
 */
WebUIJS.Prompt = function (title, defaultValue, onYes) {
    layui.layer.prompt({
        formType: 0,
        value: defaultValue,
        title: title
    }, function (value, index, elem) {

        layer.close(index);

        if (onYes) {
            onYes(value)
        }
    });
}


/**
 * 显示一个正在加载中的提示
 * @param {int} timeout 自动隐藏时间,大于0时为自动隐藏,单位为秒
 */
WebUIJS.Loading = function (timeout) {
    if (timeout && timeout > 0) {
        layui.layer.load(0, {
            time: timeout * 1000
        })
    } else {
        layui.layer.load()
    }
}

/**
 * 关闭所有loading框
 */
WebUIJS.CloseLoading = function () {
    layui.layer.closeAll('loading'); //关闭加载层
}



/**
 * 打开一个弹出窗口
 * @param {string} url 数据连接
 * @param {object} data 数据
 * @param {function(layer,index)} onSuccessCallback 显示的时候回调
 * @param {function} onCloseCallback 关闭的时候回调
 * @param {string} httpMethod http调用的方式,get或post 二选一  默认为get
 * @param {boolean} noRefreshEvent 是否禁用显示成功后刷新WebUIJS自定义的事件,默认为false
 */
WebUIJS.ModalByUrl = function (url, data, onSuccessCallback, onCloseCallback, httpMethod, noRefreshEvent,shadeOnClose=true) {
    WebUIJS.Loading();

    var layerCustomID = __getRandomID();

    if (!data || data==null) {
        data = {};
    }

    function onClose(layro, index) {
        if (onCloseCallback && onCloseCallback != null) {

            //onCloseCallback();
            __callBackFuncOrStr(onCloseCallback, layro, [layro, index]);// onSuccessCallback(layro, index);
        }
    }

    function onSuccess(layro, index) {
        WebUIJS.CloseLoading();

        var obj = {
            Update: function (html) {
                $(layro).find("").html(html);
                //重新计算弹出框高度
            }
        }

        layro.data("modal", obj);

        $(layro).data("layerindex", index);



        $(layro).addClass('layer_' + index);

        $(layro).find('.box-header .box-tools .closeModal').click(function () {
            layer.close(index);
        });

        $(layro).find('.box-header .box-tools .onMaxOrRestoreModal').click(function () {
            if (this.is(".maximizeModal")) {
                layer.full(index)
                $(this).remove('maximizeModal').addClass(".restoreModal");
            } else if (this.is(".restoreModal")) {
                layer.restore(index)
                $(this).remove('restoreModal').addClass("maximizeModal");
            }
        });

        $(layro).find('.box-header .box-tools .minimizeModal').click(function () {
            layer.min(index);
        });

        if (!noRefreshEvent) {
            WebUIJS.RefreshEvent(layro);

            $(layro).find('.box .buttonarea').find("button").each(function() {
                if ($(this).is("[type=submit]")) {
                    $(this).click(function() {
                        WebUIJS.Submit($(this).parents('form,div[data-innerform=true]').first());
                        return false;
                    });
                }
            });
        }

        __raiseEvent("system.modalsuccess", $(layro), {});

        $(layro).find("input,select").first().focus();

        if (onSuccessCallback != undefined && onSuccessCallback != null) {
            __callBackFuncOrStr(onSuccessCallback, layro, [layro, index]);// onSuccessCallback(layro, index);
        }
    }



    if (typeof options == "undefined" || options == null) {
        options = {}
    }

    var onAjaxSuccessCallback = function (html) {
  
        var layerIndex = layer.open({
            title: false,
            //area:"auto",
            type: 1,
            content: html,
            scrollbar: false,
            closeBtn: 2,
            move: ".modaltitle",
            moveType: 1,
            maxHeight: $(window).height() * 0.9,
            maxWidth: $(window).width() * 0.9,
            fixed: true,
            shadeClose: shadeOnClose,
            resize: false,
            end: onClose,
            success: function (layero, index) {
                

                $(layero).on("refresh",
                    function () {
                        var modal = $(layero).find(".modalwindow");
                        var height = $(layero).outerHeight();
                        var layerWidth = $(layero).outerWidth();
                        
                        var headerHeight = $(modal).find(".modaltitle").outerHeight();
                        var footerHeight = parseFloatEx($(modal).find(".modalfooter").outerHeight(),0);

                        $(modal).find(".modalcontent").height((height - headerHeight - footerHeight - 7) + "px");
                    });


                $(layero).trigger("refresh");

                
                //$(modal).find(".box-body").width(layerWidth + "px");

                layui.form.render();

                onSuccess(layero, index);
            }
        });

        __setRandomData(layerCustomID, layerIndex);
    }

    data["layerindex"] = layerCustomID;

    if (httpMethod === "post") {
        $.post(url,
            data,
            function (html) {
                onAjaxSuccessCallback(html);
            });
    } else {
        $.get(url,
            data,
            function (html) {
                onAjaxSuccessCallback(html);

            });
    }
}

/**
 * 初始化表单的自动添加行的功能,使用前提是,初始化的时候,该table必须有最少一行,每次增加行的时候,会使用该行的clone,并清空input和select的数据
 * @param {html element} table  用于初始化的table
 * @param {object} data 数据
 * @param {function(row,newID)} onAddRowCallback 当添加一个新行的时候的回调
 */
WebUIJS.InitAutoAddTableRow=function(table,onAddRowCallback){
    table=$(table);

    var template=table.find("tbody tr").first().clone();

    //初始化
    table.find("tbody tr").each(function () {
        $(this).find("input").first().blur(function () { //当前表格最后一行的一个文本框失去焦点的时候,判断当前文本框有没有数据
            if ($(this).val() != "" && table.find("tbody tr").last().find(":text").first().val() != ""
            ) { //如果有数据,则自动加一行
                __addnewrow(table, template);
            }
        });
    });

    var index =table.find("tbody tr").length;

    var __addnewrow=function (tbl, temploaterow) {
        var item = $(temploaterow).clone();
        index = index  + 1;
        
        var newID=(index + 10000)*-1;

        $(item).find("input,select").each(function () {

            var replacename = $(this).attr("name").replace(/_-?(\w+)/i, "_" +  newID);
            $(this).attr("name", replacename);
        });

        $(item).find("input").val('');
        $(item).find("select").val('');

        $(item).find("td span.rowindexcell").text(index);

        var cellImage=$(item).find(".cell-image");
        if(cellImage && cellImage.length>0){
            var imageCellName=cellImage.data("name");

            if (imageCellName){
                imageCellName=imageCellName.replace(/_-?(\w+)/i, "_" +  newID);
                $(cellImage).data("name", imageCellName);
            }

            $(cellImage).find("input").remove();
        }

        if ($(tbl).is(".webui_table")) {
            $(tbl).find("tbody").append(item);
            $(tbl).simpleTable().refresh();
        } else {
            var jqtable = $(tbl).data("jquerydatatable");

            jqtable.row.add(item).draw();
        }

        



        //添加失去焦点
        $(item).find("input").first().blur(function () {
            if ($(this).val() != "" && tbl.find("tbody tr").last().find(":text").first().val() != ""
            ) { //如果有数据,则自动加一行
                __addnewrow(tbl, tbl.find("tbody tr").last());
            }
        });

        WebUIJS.RefreshEvent(item);

        if(onAddRowCallback){
            onAddRowCallback(item,newID);
        }
    }
}


WebUIJS.CloneRow = function(table, index,onSuccessCallback) {
    table = $(table);

    if (!index) {
        index = 0;
    }

    var template = $(table.find("tbody tr:eq(" + index +")").first().clone());

    var newID = (index + 10000) * -1;
    $(template).find("input,select").each(function () {

        var replacename = $(this).attr("name").replace(/_-?(\w+)/i, "_" + newID);
        $(this).attr("name", replacename);
    });

    $(item).find("input").val('');
    $(item).find("select").val('');

    $(item).find("td span.rowindexcell").text(index);

    var cellImage = $(item).find(".cell-image");
    if (cellImage && cellImage.length > 0) {
        var imageCellName = cellImage.data("name");

        if (imageCellName) {
            imageCellName = imageCellName.replace(/_-?(\w+)/i, "_" + newID);
            $(cellImage).data("name", imageCellName);
        }

        $(cellImage).find("input").remove();
    }

    table.find("tbody").append(template);

    WebUIJS.RefreshEvent(template);

    if (onSuccessCallback) {
        onSuccessCallback(table, template);
    }
}


/**
 * 打开一个弹出窗口,直接使用指定的元素,不经过网络获取
 * @param {htmlelement} element 要弹出窗体的元素
 * @param {function(layer,index)} onSuccessCallback 成功后回调
 * @param {function} onCloseCallback 关闭后,回调
 * @param {bool} noRefreshEvent 打开后是否刷新控件事件,默认为false
 */
WebUIJS.ModalByElement = function (element, onSuccessCallback, onCloseCallback, noRefreshEvent) {

    function onClose() {
        if (onCloseCallback != undefined && onCloseCallback != null) {
            onCloseCallback();
        }
    }

    function onSuccess(layro, index) {
        WebUIJS.CloseLoading();

        $(layro).data("layerindex", index);

        if (onSuccessCallback != undefined && onSuccessCallback != null) {
            onSuccessCallback(layro, index);
        }

        $(layro).addClass('layer_' + index);

        $(layro).find('.box-header .box-tools .closeModal').click(function () {
            layer.close(index);
        });

        $(layro).find('.box-header .box-tools .onMaxOrRestoreModal').click(function () {
            if (this.is(".maximizeModal")) {
                layer.full(index)
                $(this).remove('maximizeModal').addClass(".restoreModal");
            } else if (this.is(".restoreModal")) {
                layer.restore(index)
                $(this).remove('restoreModal').addClass("maximizeModal");
            }
        });

        $(layro).find('.box-header .box-tools .minimizeModal').click(function () {
            layer.min(index);
        });

        if (!noRefreshEvent) {
            WebUIJS.RefreshEvent(layro);
        }

        __raiseEvent("system.modalsuccess", $(layro), {});
    }

    var layerIndex = layer.open({
        title: false,
        //area:"auto",
        type: 1,
        content: element,
        scrollbar: false,
        closeBtn: 2,
        move: ".modaltitle",
        moveType: 1,
        maxHeight: $(window).height() * 0.8,
        maxWidth: $(window).width() * 0.8,
        fixed: true,
        shadeClose: true,
        end: onClose,
        success: function (layero, index) {
            var modal = $(layero).find(".modalwindow");

            var height = $(layero).outerHeight();
            var headerHeight = $(modal).find(".modaltitle").outerHeight();
            var footerHeight = $(modal).find(".modalfooter").outerHeight();

            $(layero).find(".modalcontent").height((height - headerHeight - footerHeight - 3) + "px");
            layui.form.render();

            onSuccess(layero, index);
        }
    });

    // var layerIndex = layer.open({
    //     type: 1,
    //     title: false,
    //     content: element,
    //     scrollbar: false,
    //     shadeClose: false,
    //     move: '.box-header',
    //     moveType: 1,
    //     area: "auto",
    //     success: onSuccess,
    //     fixed: true,
    //     end: onClose,
    //     //zIndex: layer.zIndex //重点1
    // });
}

WebUIJS.CloseModal = function (layerIndex) {
    if (layerIndex) {
        layer.close(__getRandomData(layerIndex));
    } else {
        WebUIJS.CloseAllModal();
    }
    
}

WebUIJS.CloseAllModal = function () {
    layer.closeAll('page');
}

/**
 * 打开一个数据选择器,并返回选择后的数据,selectedCallback=function
 * @param {string} url 
 * @param {function (data)} selectedCallback : 如果有选择数据,则调用该回调函数,data为选中的数据数组
 * @param {object} options : 可选参数, StoreInCache:bool 为true时,如果在多选模式下,翻页时,将记录所选择的项目 
 * @returns {} 
 */
WebUIJS.ShowDataPicker = function (url, data, selectedCallback, onShowCallback, options, sender) {

    if (!sender) {
        sender = window;
    } else {
        sender = $(sender);
    }

    var layroIndex = 0;

    var cleanCacheWhenSearch = true;

    var opt = {
        method: "get",
        CleanSelectedCacheWhenSearch: true,
        orderBy: "",     //排序字段
        orderByType: 0 ,    //0=升序,-1=降序,
        selectedAreaTitle :""
    }

    $.extend(opt, options);

    //每次窗体更新时,自动刷新事件
    var refreshEvent = function (layro) {
        var pickerheight = $(layro).find(".datapicker").height();
        var qbHeight = parseFloatEx($(layro).find(".querybox").outerHeight(true), 0);
        var pager = parseFloatEx($(layro).find(".tablepagination").outerHeight(true), 0);
        var headerHeight = parseFloatEx($(layro).find(".modaltitle").outerHeight(true), 0);
        var footerHeight = parseFloatEx($(layro).find(".datapickerfooter").outerHeight(true), 0);
        var selectedAreaHeight = parseFloatEx($(layro).find(".dataPickerSelectedArea").outerHeight(true), 0);

        $(layro).find(".datapickercontent").height(pickerheight - headerHeight - footerHeight);
        var pickerContentHeight = $(layro).find(".datapickercontent").outerHeight(true);
        
        $(layro).find(".dataPickerDataList").height(pickerContentHeight - qbHeight - selectedAreaHeight);
        var dataListHeight = $(layro).find(".dataPickerDataList").outerHeight(true);
        
        $(layro).find(".dataPickerDataList .jqtable").each(function() {
            $(this).DataTable().draw();
        }) 

        $(layro).find(".dataPickerDataList .webui_table").each(function() {
            //$(this).simpleTable().refresh();
            var html = $(this.outerHTML).removeClass("wraped").data("scrolly", dataListHeight - pager - 2);
            $(this).closest(".webui_table_wrapper").replaceWith(html);
            WebUIJS.RefreshEvent(html);
        });
        

        $(layro).find(".datapickercontent .table>tbody>tr").each(function() {
            var tr = $(this);

            tr.closest(".datapicker").find(".dataPickerSelectedArea .dataPickerSelectedItems input[type=hidden]").each(function() {
                var checkbox = tr.find(":checkbox");
                if (checkbox.length > 0 && checkbox.val() == $(this).val() && !checkbox.is(":checked")) {
                    checkbox.siblings(".layui-form-checkbox").click();
                    $(this).closest("tr").data("row", tr);
                }
            });

            tr.find("input[type=hidden],:checkbox").change(function() {

                if ($(this).is(":checkbox")) {
                    var table = $(this).closest(".datapicker").find(".dataPickerSelectedArea .dataPickerSelectedItems");
                    var row = $(this).closest("tr");
                    if ($(this).is(":checked")) {

                        var tdlist = row.find("td").slice(1);

                        var newTr = $(
                            "<tr><td><a class=\"removebtn\"><input type=\"hidden\" ><i class=\"fa fa-trash-o\"></i></a></td></tr>");

                        newTr.find(":hidden").val($(this).val());

                        tdlist.each(function() {
                            newTr.append($(this).clone());
                        });

                        newTr.data("row", row);

                        table.find("tbody").append(newTr);
                        
                    } else {
                        table.find("tbody tr").each(function() {
                            var targetrow = $(this).data("row");

                            if (targetrow && targetrow[0] == row[0]) {
                                $(this).remove();
                                return false;
                            }
                        });

                    }

                    refreshPickerSelectedAreaItems(table);

                } else if ($(this).is("input[type=hidden]")) {
                    //TODO:回调success函数
                    var d = [];

                    d.push($.parseJSON($.htmldecode($(this).val())));

                    //if (selectedCallback && isString(selectedCallback) && selectedCallback != "") {
                    //    new Function(selectedCallback).call(this, d);
                    //} else if (isFunction(selectedCallback)) {
                    //    selectedCallback.call(sender, d);
                    //}

                    if (selectedCallback) __callBackFuncOrStr(selectedCallback, sender, [d]);

                    layui.layer.close(layroIndex);
                    //selectedCallback(d);
                }

            });


            tr.find("td").each(function(index, e) {
                if (index > 0 || $(this).find('input').length<=0) {
                    $(this).click(function() {
                        {
                            var radio = tr.find("input[type=hidden]");

                            if (radio.length > 0) {
                                //radio.click();
                                radio.trigger("change");
                                return false;
                            }

                            var checkbox = tr.find(".layui-form-checkbox");
                            if (checkbox.length > 0) {
                                checkbox.click();
                                //return false;
                            }

                        }
                    })
                }
            })


        });

        var table=$(layro).find(".dataPickerDataList table.table");
        var tbody=$(table).find("tbody");
        $(table).find("th.selectcol :checkbox.selectall").change(function() {
            var th = $(this).closest("th");
            var ck = $(this);

            var index = table.find("thead th").index(th);

            tbody.find("tr").each(function() {
                if (ck.is(":checked")) {
                    $(this).find("td:eq(" + index + ") .layui-form-checkbox:not(.layui-form-checked)").click();
                } else {
                    $(this).find("td:eq(" + index + ") .layui-form-checkbox.layui-form-checked").click();
                }
            });

            // tbody.find("tr td:eq(" + index + ") .layui-form-checkbox").each(function(){
            //     $(this).click();
            // })
        });

        onLinkOrFormRequest(layro);
    }

    var refreshSelectedRowEvent = function (row) {

        $(row).find("a.removebtn").click(function(e) {
            var tr = $(this).closest("tr");

            var data = $(tr).data("row")[0];

            //$(this).closest("tr").remove();

            $(this).closest(".datapicker")
                .find(".datapickercontent .table>tbody>tr")
                .each(function() {
                    if ($(this)[0] == data) {
                        $(this).find("td").first().find(".layui-form-checkbox").click();
                        return false;
                    }

                });

            $(this).closest("tr").remove();

            refreshSelectionAreaTitle($(this).closest(".datapicker"));
        });
    }

    //点击跳转或者点击按钮提交
    var onLinkOrFormRequest = function (layro) {
        
        var request = function (url, data, httpMethod, onSuccessCallback) {
            var timeout = 0;
            var selectedArea = $(layro).find(".box.dataPickerSelectedArea");

            if (!selectedArea.is(".collapsed-box")) {
                selectedArea.boxWidget('toggle');
                timeout = 200;
            }

            setTimeout(function() {
                __httpGetOrPostDataByHtml(url, data,
                    function (html) {
                        var newHtml = $(html);

                        $(layro).find(".querybox").replaceWith(newHtml.find(".querybox"));
                        $(layro).find(".dataPickerDataList").replaceWith(newHtml.find(".dataPickerDataList"));

                        WebUIJS.RefreshEvent($(layro).find(".querybox"));
                        WebUIJS.RefreshEvent($(layro).find(".dataPickerDataList"));

                        refreshEvent(layro);

                        if (onSuccessCallback) {
                            onSuccessCallback.call(layro);
                        }
                    }, null, httpMethod);
            }, timeout);            
        }

        $(layro).find("a[href]").each(function () {
            var that = $(this);
            var href = that.attr("href");

            if (startWith(href, "#") || startWith(href,"javascript:")) {
                return;
            }

            that.data("href", href);

            that.attr("href", "#");

            //var selectedArea = $(layro).find(".box.dataPickerSelectedArea");

            //if (!selectedArea.is(".collapsed-box")) {
            //    selectedArea.boxWidget('toggle');
            //}

            __raiseEvent("system.datapicker.beforesubmit", $(layro), {});

            //that.removeAttr("href");
            that.click(function() {
                request(href, null, "get", function() {
                    __raiseEvent("system.datapicker.submitsuccess", $(this), {});
                });
            });


        });

        $(layro).find(".pagerinput").each(function () {
            var pager = $(this).closest(".tablepagination").find(".pagination");
            var urlTemplate = pager.data("url-format");

            __raiseEvent("system.datapicker.beforesubmit", $(layro), {});

            $(this).keydown(function (event) {
                if (event.keyCode == 13) {
                    var value = $(this).val();
                    if (parseIntEx(value, 0) <= 0) {
                        return;
                    }

                    request(urlTemplate.replace("__pageIndex__", value), null, "get", function () {
                        __raiseEvent("system.datapicker.submitsuccess", $(this), {});
                    });
                }
            });
        });

        $(layro).find('form,div[data-innerform="True"]').each(function() {
            var that = $(this);

            var href = __getFormOrDivUrl(that);
            var method = __getFormOrDivMethod(that);

            if (that.is("form")) {
                $(that).submit(function(event) {
                    event.preventDefault();

                    //var selectedArea = $(layro).find(".box.dataPickerSelectedArea");

                    //if (!selectedArea.is(".collapsed-box")) {
                    //    selectedArea.boxWidget('toggle');
                    //}

                    var args = $(that).serialize();

                    __raiseEvent("system.datapicker.beforesubmit", $(layro), {});

                    request(href, args, method,function() {
                        __raiseEvent("system.datapicker.submitsuccess", $(this), {});
                    });

                    return false;
                });
            } else {
                that.data("submit",
                    function() {
                        var args = $(that).serialize();

                        //var selectedArea = $(layro).find(".box.dataPickerSelectedArea");

                        //if (!selectedArea.is(".collapsed-box")) {
                        //    selectedArea.boxWidget('toggle');
                        //}

                        __raiseEvent("system.datapicker.beforesubmit", $(layro), {});

                        request(href, args, method,function() {
                            __raiseEvent("system.datapicker.submitsuccess", $(this), {});
                        });
                    });
            }
        });
    }

    //窗体显示时,第一次初始化事件调用
    var firstTimeRefreshEvent = function (layro) {

        try {
            $(layro).find('.box.dataPickerSelectedArea').boxWidget({
                animationSpeed: 200
            });
        } catch (e) {

        } 
        
        

        var dataPickerDataListHeight = $(layro).find(".dataPickerDataList").outerHeight(true);

        $(layro).find(".dataPickerSelectedArea>.box-body").css("max-height", dataPickerDataListHeight);


        $(layro).find('.box.dataPickerSelectedArea').on('expanded.boxwidget',
            function() {
                //$(layro).find(".dataPickerDataList").slideUp("fast");
                $(layro).find(".dataPickerDataList").hide();
            });

        $(layro).find('.box.dataPickerSelectedArea').on('collapsed.boxwidget',
            function() {
                $(layro).find(".dataPickerDataList").slideDown(200);
                //$(layro).find(".dataPickerDataList").show(300)
            });


        $(layro).find(".box.dataPickerSelectedArea>.box-header").click(function(e) {
            if (e.target == this || e.target.tagName == "H5") {

                $(this).closest(".box").boxWidget('toggle');
            }
        });


        $(layro).find(".dataPickerSelectedArea .clearselected").closest('button').click(function (e) {
            $(this).closest(".box").find(".dataPickerSelectedItems>tbody").empty();

            $(layro).find(".datapickercontent .table>tbody>tr").each(function() {
                var checkbox = $(this).find("td").first().find(".layui-form-checkbox");
                if (checkbox.is(".layui-form-checked")) {
                    checkbox.click();
                }
            });

            refreshPickerSelectedAreaItems($(this).closest(".datapicker .dataPickerSelectedArea"))
        });

        $(layro).find(".dataPickerSelectedArea .dataPickerSelectedItems tbody tr").each(function () {
            refreshSelectedRowEvent(this);
        });

        $(layro).find(".datapickerfooter .okbutton").click(function () {
            var array = [];

            $(this).closest(".datapicker").find(".dataPickerSelectedItems input[type=hidden]").each(function() {
                array.push($.parseJSON($.htmldecode($(this).val())));
            });

            if (array.length <= 0) {
                WebUIJS.Alert("选择项不能为空");
                return false;
            }


            if (selectedCallback) __callBackFuncOrStr(selectedCallback, sender, [array]);

            //if (selectedCallback && isString(selectedCallback) && selectedCallback != "") {
            //    new Function(selectedCallback).call(this, array);
            //} else if (isFunction(selectedCallback)) {
            //    selectedCallback.call(sender, array);
            //}

            layui.layer.close(layroIndex);
        });

        $(layro).find(".datapickerfooter .cancelbutton").click(function() {
            layer.close($(layro).data("layerindex"));
        });

        //var selectedAreaTitle = selectedAreaTitle.;

        //opt.selectedAreaTitle = selectedAreaTitle;
        refreshSelectionAreaTitle(layro);
        //$(layro).find(".dataPickerSelectedArea .selectedAreaTitle").text(opt.selectedAreaTitle.replace("{0}", 0));
    }

    var refreshPickerSelectedAreaItems=function(tbl) {

        var rows = $(tbl).find("tbody tr");


        $(tbl).find('tbody').detach("tr");
        var tbody = $(tbl).find('tbody');
        if (rows.length <= 0) {
            return;
        }

        var query = Enumerable.from(rows);

        if (opt.orderBy != "") {
            var orderByKeyColIndex = getTableColumnIndex(tbl, "." + opt.orderBy);

            if (opt.orderByType == 0) {
                query = query.orderBy("r=>$(r).find(\"td:eq(" + orderByKeyColIndex + ")\").text()");
            } else {
                query = query.orderByDescending("r=>$(r).find(\"td:eq(" + orderByKeyColIndex + ")\").text()");
            }
            
        }

        var indexColIndex = getTableColumnIndex(tbl, ".indexcol");

        query = query.toArray();

        for (var i = 0; i < query.length; i++) {
            var row = query[i];

            if (indexColIndex >= 0) {
                $(row).find("td:eq(" + indexColIndex + ")").text(i+1);
            }

            tbody.append(row);

            refreshSelectedRowEvent(row);
        }
        
        //$(tbl).closest(".dataPickerSelectedArea").find(".selectedAreaTitle").text(opt.selectedAreaTitle.replace("{0}", rows.length));

        refreshSelectionAreaTitle($(tbl).closest(".datapicker"));
    }

    var refreshSelectionAreaTitle = function (layro) {
        var rows = $(layro).find(".dataPickerSelectedArea").find("table tbody tr").length;

        $(layro).find(".dataPickerSelectedArea .selectedAreaTitle").text(opt.selectedAreaTitle.replace("{0}", rows));
    }


    WebUIJS.ModalByUrl(url,
        data,
        function(layro, index) {
            layroIndex = index;



            //if (isString(onShowCallback) && onShowCallback != "") {
            //    new Function(onShowCallback).call(sender, layro, index);
            //} else if (isFunction(onShowCallback)) {
            //    onShowCallback.call(sender, layro, index);
            //}

            if (toStringEx(opt.orderBy)=="") {
                opt.orderBy = toStringEx($(layro).find(".datapicker").data("orderby"));
                opt.orderByType = parseIntEx(toStringEx($(layro).find(".datapicker").data("orderbytype")));
            }

            if (isEmpty(opt.selectedAreaTitle)) {
                opt.selectedAreaTitle = $(layro).find(".datapicker").data("selectedareatitle");

                if (isEmpty(opt.selectedAreaTitle)) {
                    opt.selectedAreaTitle = "已选择:{0}";
                }
                
            }

            refreshEvent(layro);

            firstTimeRefreshEvent(layro);

            if (onShowCallback) __callBackFuncOrStr(onShowCallback, $(layro));

            __raiseEvent("system.datapicker.shown", $(layro), {});
        });
}

//显示一个图片查看器
WebUIJS.ShowImageViewer = function (url, title, onShowCallback, onCloseCallback) {
    if (!title) {
        title = "图片查看";
    }

    var imgs = [];

    if (isArray(url)) {
        for (var i = 0; i < url.length; i++) {
            imgs.push({
                "src": url[i], //原图地址
                "thumb": url[i] //缩略图地址
            });
        }

        layer.photos({
            photos: {
                "title": title, //相册标题
                "id": 123, //相册id
                "start": 0, //初始显示的图片序号，默认0
                "data": imgs   //相册包含的图片，数组格式
            },
            tab: function (pic, layero) {
                console.log(pic); //当前图片的一些信息
            }
        });
    } else {
        //var img = $("<img >");

        //$(img).height($(window).height() * 0.4);
        //$(img).width($(window).width() * 0.4);

        if (isEmpty(url)) {
            WebUIJS.Toast("无图片");
            return;
        }

        layer.open({
            type: 1,
            title: title,
            //content: "<img width=\"" + $(window).width() * 0.4 + "px\" height=\"" + $(window).height() * 0.4 +"px\">" ,
            content: "<img style='width:auto;height:auto;max-width:100%;max-height:100%;position:absolute;top:0;left:0;right:0;bottom:0;margin:auto;'>" ,
            //closeBtn :true,
            //area: [($(window).width() * 0.4) + 'px', (($(window).height() * 0.4) + 52) + 'px'],
            area: [($(window).width() * 0.4) + 'px', $(window).height() * 0.6 + 'px'],
            fixed: true,
            shadeClose:true,
            success: function (layero, index) {
                var img = $(layero).find("img");
                //_autoScaleImage(img);
                img.attr("src", url);
            }
        });
    }
}

WebUIJS.Get = function (url, data, onsuccess, onerror, oncompleted, onbeforceSend) {
    $.ajax({
        url: url,
        async: true,
        cache: false,
        type: "GET",
        data: data,
        beforeSend: function () {
            if (typeof (onbeforceSend) != "undefined" && onbeforceSend != null) {
                onbeforceSend();
            }
        },
        success: function (result, status, xhr) {
            if (typeof (onsuccess) != "undefined" && onsuccess != null) {
                onsuccess(result, status, xhr);
            }

        },
        error: function (xhr, status, error) {
            if (typeof (onerror) != "undefined" && onerror != null) {
                onerror(xhr, status, error);
            }
        },
        complete: function (xhr, status) {
            if (typeof (oncompleted) != "undefined" && oncompleted != null) {
                oncompleted(xhr, status);
            }
        }
    });
}

WebUIJS.PostJson = function (url, data, onsuccess, onerror, oncompleted, onbeforceSend) {
    $.ajax(url, {
        async: true,
        cache: false,
        type: "POST",
        data: data,
        dataType: "json",
        beforeSend: function () {
            if (typeof (onbeforceSend) != "undefined" && onbeforceSend != null) {
                onbeforceSend();
            }
        },
        success: function (result, status, xhr) {
            if (typeof (onsuccess) != "undefined" && onsuccess != null) {
                onsuccess(result, status, xhr);
            }

        },
        error: function (xhr, status, error) {
            if (typeof (onerror) != "undefined" && onerror != null) {
                onerror(xhr, status, error);
            }
        },
        complete: function (xhr, status) {
            if (typeof (oncompleted) != "undefined" && oncompleted != null) {
                oncompleted(xhr, status);
            }
        }
    });

}


WebUIJS.Post = function (url, data, onsuccess, onerror, oncompleted, onbeforceSend) {

    $.ajax({
        url: url,
        async: true,
        cache: false,
        type: "POST",
        data: data,
        //dataType: "json",
        beforeSend: function () {
            if (typeof (onbeforceSend) != "undefined" && onbeforceSend != null) {
                onbeforceSend();
            }
        },
        success: function (result, status, xhr) {
            if (typeof (onsuccess) != "undefined" && onsuccess != null) {
                onsuccess(result, status, xhr);
            }

        },
        error: function (xhr, status, error) {
            if (typeof (onerror) != "undefined" && onerror != null) {
                onerror(xhr, status, error);
            }
        },
        complete: function (xhr, status) {
            if (typeof (oncompleted) != "undefined" && oncompleted != null) {
                oncompleted(xhr, status);
            }
        }
    });

}

/**
 * 直接弹出一个上传文件的框,并在上传过程中,右下角有进度条
 * @param {string} uploadUrl  服务器地址
 * @param {object} options  参数 {onSuccess=function(data), onBeforeUpload=function(file) 返回false,取消上传,  onError=function(error),,onCompleted=function(data),fieldName=string,maxFileSize=0,accept="",showProgress=true //显示进度条}
 */
WebUIJS.ShowUploadFile = function (uploadUrl, options) {

    var defaultOpts = {
        onSuccess: null,
        onError: null,
        onCompleted: null,
        onBeforeUpload: function(file) {return true},
        fieldName:"file",
        maxFileSize: 0,
        accept: "*/*",
        showProgress:true
    }

    var opt = $.extend({}, defaultOpts, options);


    if (!opt.fieldName || opt.fieldName=="") {
        opt.fieldName = "file";
    }

    var file = $('<input style="display:none" type="file" name="' + opt.fieldName + '"/>');

    if (opt.accept && opt.accept!=="") {
        file.attr("accept", opt.accept);
    }

    $("body").append(file);

    file[0].onchange=function () {
        if (this.files.length <= 0) {
            file.remove();
            return false;
        }

        if (opt.maxFileSize && opt.maxFileSize > 0 && this.files[0].size > opt.maxFileSize) {
            file.remove();
            WebUIJS.Alert("文件太大,不能上传");
            return false;
        }

        if (opt.onBeforeUpload) {
            if (opt.onBeforeUpload(file) === false) {
                file.remove();
                return false;
            }
        }

        var progress = null;
        var progressText = null;

        if (opt.showProgress) {
            var col = $(".fileUploadNotify");

            if (col.length <= 0) {
                col = $('<div class="fileUploadNotify"></div>');
                $('body').append(col);
            }

            var block = $(
                '<div class="uploadStateItem"><div class="info-box bg-green"><div class="info-box-content"><span class="info-box-number" style=\"font-weight: 100;font-size: 16px;\">' + this.files[0].name + '</span><div class="progress"><div class="progress-bar" style="width: 0%"></div></div><span class="progress-description">上传进度:<span class="progress-description-text">0%</span></span></div></div>)');

            progress = $(block).find(".progress-bar");
            progressText = $(block).find(".progress-description-text");

            col.append(block);
        }
        

        

        __uploadFileToServer(this,
            uploadUrl,
            {
                onProgree: function (value) {
                    if (progress) {
                        $(progress).css("width", value + "%");
                        $(progressText).text(value.toFixed(1) + "%");
                    }
                    
                },
                onSuccess: function (data) {
                    $(progress).css("width", "100%");
                    $(progressText).text("上传完成");
                    $(file).remove();

                    if (opt.onSuccess)
                        opt.onSuccess(data);
                    
                },
                onError: function (error) {
                    block.find("info-box").removeClass("bg-green").addClass("bg-red");

                    $(progress).css("width", "100%");
                    $(progressText).text("上传错误");

                    if (opt.onError)
                        opt.onError(error);
                },
                onComplete: function(data)
                {
                    window.setTimeout(function () {
                            block.fadeOut().remove();
                        },
                        5000);

                    if (opt.onCompleted)
                        opt.onCompleted(data);
                },
                fieldName: opt.fieldName
            });
        
    };

    try {
        file.click();
    } catch (e) {
        var p = 0;
    } 
    
}



WebUIJS.on = function(eventName, callback) {
    var handlers = eventHandlers[eventName];
    handlers.push(callback);
}

var dropdownMenu;
WebUIJS.RefreshEvent = function (el, onsuccess) {
    var panelBox = function (collection) {
        collection = $(collection);

        if (!$(collection).is('.box.webui-ctrl-panelbox')) {
            collection = $(collection).find('.box.webui-ctrl-panelbox');
        }

        $(collection).each(function () {
            $(this).boxWidget({
                animationSpeed: 200
            });

            //$(this).find("button[data-widget='collapse']").each(function (e) {
            //    e.stopPropagation();
            //});

            $(this).find("button[data-widget='remove-confirm']").click(function () {
                var btnRemove = $(this).siblings("button[data-widget='remove']");
                var tips = $(this).data("tips");
                if (tips === undefined || tips === null || tips == "") {
                    btnRemove.click();
                } else {
                    if (confirm(tips)) {
                        btnRemove.click();
                    }
                }
            });
        });


    }

    //刷新异步Form事件
    var ajaxForm = function (collection, onsuccess) {
        collection = $(collection);

        if (!($(collection).is('form[data-ajax=True],div[data-innerform="True"]'))) {
            collection = $(collection).find('form[data-ajax=True],div[data-innerform="True"]');
        }

        collection.each(function() {
            if ($(this).is("[webui-ignore]")) {
                return;
            }

            var that = $(this);

            if ($(this).is("form[data-ajax=True]")) {
                var updateEl = $(this).data("updateelemid");

                var opt = {
                    cache: false,

                    beforeSerialize: function($form, option) {
                        var files = $($form).find('.imageuploadfield :file');

                        files.each(function() {
                            var $this = $(this);

                            if (isEmpty($this.val())) {
                                $this.data("tmpname", $this.attr("name"));
                                $this.attr("name", null);
                            }
                        });
                    },
                    beforeSubmit: function(arr, $form, options) {
                        if (typeof ($form.valid) != "undefined" && $form.valid != null) {
                            if (!$form.valid()) {
                                return false;
                            }
                        }

                        $(this).data("disabled", "true");
                        //yer.load();
                        WebUIJS.Loading();

                        var files = $($form).find('.imageuploadfield :file[data-tmpname]');

                        files.each(function() {
                            var $this = $(this);

                            $this.attr("name", $this.data("tmpname"));
                        });


                    },
                    //target: $('#' + updateEl),
                    //replaceTarget:true,
                    //iframe: true,
                    success: function(responseText, statusText) {
                        //$.ladda('stopAll');
                        WebUIJS.CloseLoading();

                        if (isEmpty(responseText)) {
                            $('#' + updateEl).empty();
                            return;
                        }

                        var targetEl = $('#' + updateEl);
                        targetEl.empty();

                        var item = $(responseText).is("#" + updateEl) ? $(responseText) : $(responseText).find("#" + updateEl);

                        if (item.length > 0) {
                            targetEl.replaceWith(item);
                        } else {
                            targetEl.html(responseText);
                        }

                        var newItem = $('#' + updateEl);

                        WebUIJS.RefreshEvent(newItem);

                        //yer.closeAll("loading");

                        $(this).data("disabled", null);
                        
                        if (onsuccess != undefined && onsuccess != null) {
                            onsuccess(newItem);
                        }

                        $('#' + updateEl).closest(".layui-layer").trigger("refresh");
                    },
                    error: function() {
                        WebUIJS.CloseLoading();
                        //$.ladda('stopAll');
                        $(this).data("disabled", null);
                    }
                }

                $(this).submit(function() {
                    if ($(this).data("disabled") === "true") {
                        return false;
                    } else {
                        //$(this).data("disabled", "true");
                        return true;
                    }
                });

                $(this).ajaxForm(opt);
            } else if ($(this).is('div[data-innerform="True"]')) {
                var that = $(this);
                $(this).data("submit",
                    function() {
                        if ($(that).data("disabled") === "true") {

                            return false;
                        } else {
                            $(that).data("disabled", "true");
                        }

                        if (typeof (that.valid) != "undefined" && that.valid != null) {
                            if (!that.valid()) {
                                return false;
                            }
                        }

                        var method = $(that).attr("method");
                        var action = $(that).attr("action");
                        var isAjax = $(that).data("ajax");
                        var updateEl = $(that).data("updateelemid");

                        if (isEmpty(method)) {
                            method = "get";
                        }

                        if (isEmpty(action)) {
                            action = window.location.href;
                        }

                        if (isEmpty(isAjax)) {
                            isAjax = "True";
                        }

                        isAjax = isAjax === "True";

                        if (isEmpty(updateEl)) {
                            updateEl = "";
                        }

                        var formData = new FormData();

                        $(this).find("input,textarea,select").each(function() {
                            if ($(this).attr("name") == "") {
                                return;
                            }

                            if ($(this).is("input[type=file]")) {
                                formData.append($(this).attr("name"), $(this)[0].files[0]);
                            } else {
                                formData.append($(this).attr("name"), $(this).val());
                            }
                        });

                        //var data = $(this).find("input,textarea,select").serialize();

                        $.ajax({
                            async: true,
                            data: formData ,//data,
                            type: method,
                            url: action,
                            dataType: "html",
                            contentType: "",
                            success: function(responseText, textStatus, jqXHR) {

                                if (isEmpty(responseText)) {
                                    $('#' + updateEl).empty();
                                    return;
                                }

                                var targetEl = $('#' + updateEl);
                                targetEl.empty();

                                var item = $(responseText).is("#" + updateEl) ? $(responseText) : $(responseText).find("#" + updateEl);

                                if (item.length > 0) {
                                    targetEl.replaceWith(item);
                                } else {
                                    targetEl.html(responseText);
                                }

                                var newItem = $('#' + updateEl);

                                WebUIJS.RefreshEvent(newItem);

                                if (onsuccess != undefined && onsuccess != null) {
                                    onsuccess(newItem);
                                }
                            },
                            beforeSend: function(xhr) {
                                WebUIJS.Loading();
                            },
                            complete: function(jqXHR, textStatus) {
                                $(that).data("disabled", null);
                                //$.ladda('stopAll');
                                WebUIJS.CloseLoading();
                            }
                        });
                    });
            }
        });
    }

    var querybox = function (collection) {
        if (!$(collection).is(".querybox")) {
            collection = $(collection).find(".querybox");
        }

        $(collection).each(function () {
            var that = $(this);

            $(this).find(".querybuttonarea").each(function () {
                $(this).css("margin-top", $(that).height() - 10 - $(this).height());
            });
        })


    }

    var text = function (collection) {
        collection = $(collection);

        if (!collection.is("input[data-autoselected=True]")) {
            collection = collection.find("input[data-autoselected=True]");
        } 

        $(collection).each(function () {
            $(this).focus(function () {
                $(this).select();
            });
        });

    }

    var button = function (collection) {
        $(collection).find('button,a.btn').each(function () {
            var that = $(this);

            if (that.is('[webui-ignore]') || that.is(".note-btn")) {
                return true;
            }

            var s = $(this).attr("onclick");

            if (isString(s) && s !== "") {
                $(this).data("onclick", s);
                $(this).attr("onclick", null);
                //(function () { return eval(s); }).call(this);
            }

            var click = function(e) {
                var that = $(this);

                if ($(this).is('.dropdown-toggle')) {
                    return true;
                }

                if ($(this).data("disabledafterclick") === "True") {
                    $(this).attr("disabled", "disabled");
                }

                var s = $(this).data("onclick");

                if (isString(s) && s !== "") {
                    if (new Function(s).call(this) == false) {
                        return false;
                    }
                }

                if (isString($(this).data("forform")) && $(this).data("forform") !== "") {

                    var closestEl = $($(this).data("forform"));

                    return WebUIJS.Submit(closestEl);

                } else if ($(this).is("[type=submit]")) {

                    //var closestEl = $(this).closest('form,div[data-innerform="True"]');
                    //$(this).ladda('start');

                    if (WebUIJS.Submit(this) == false) {
                        e.preventDefault();
                        return false;
                    }

                    return true;
                }

                if ($(this).is(".datapickerbtn")) {
                    var url = that.data("showdatapicker");
                    var selectedcallback = that.data("selectedcallback");
                    var fillToTextFieldName = that.data("filltotitle");
                    var fillToValueFieldName = that.data("filltovalue");
                    var showcallback = that.data("showcallback");
                    var option = that.data("option");
                    var fillconfig = that.data("fillconfig");
                    var orderby = that.data("orderby");
                    var orderbytype = parseIntEx(that.data("orderbytype"), 0);

                    option.orderBy = orderby;
                    option.orderByType = orderbytype;

                    //if (isObject(fillconfig) && fillconfig != null) {
                    var backupSelectCallback = selectedcallback;
                    selectedcallback = function(data) {


                        if (isObject(fillconfig) && fillconfig != null) {
                            try {
                                WebUIJS.FillDataToControl(data, fillconfig);
                            } catch (e) {

                            }
                        }

                        try {
                            if (backupSelectCallback) __callBackFuncOrStr(backupSelectCallback, this, [data]);

                        } catch (e) {

                        }

                        if (isArray(data)) {
                            data = data[0];
                        }

                        if (isString(fillToTextFieldName) && fillToTextFieldName !== "") {
                            WebUIJS.SetElementValue($(that).closest(".form-group").find(":text.field-title"),
                                data[fillToTextFieldName]);
                        }

                        if (isString(fillToValueFieldName) && fillToValueFieldName !== "") {
                            WebUIJS.SetElementValue($(that).closest(".form-group").find("input.filed-value"),
                                data[fillToValueFieldName]);
                        }
                    }
                    
                    WebUIJS.ShowDataPicker(url, {}, selectedcallback, showcallback, option, that);
                }
            };

            $(this).click(debounceCallfirst(click, 500, $(this), null));

        });
    }

    var selector = function (collection) {
        $(collection).find("select").each(function () {
            if ($(this).is("[webui-ignore]")) {
                return;
            }

            if ($(this).is("[multiple]")) {
                var maxSelectionSize = parseIntEx($(this).data("maxselectionsize"));

                var opt = {
                    dropdownParent: $(".modalwindow"),
                    width: "element",
                    placeholder: $(this).data("placeholder")
                };

                if (maxSelectionSize > 0) {
                    opt["maximumSelectionSize"] = maxSelectionSize;
                }

                $(this).select2(opt);
            }

            var onchangedScript =$(this).data("onchanged");


            $(this).change(function () {
                if (onchangedScript) {
                    __callBackFuncOrStr($(this).data("onchanged"), $(this));
                }

                if ($(this).is('select[data-autosubmit=True]')) {
                    WebUIJS.Submit($(this).closest('form'));
                }

            });
        });
    }

    var textEditor = function (collection) {
        try {
            $(collection).find(".summernote").destroy();
        } catch (e) {

        }

        if (!$(this).summernote) {

        }

        $(collection).find(".summernote").each(function () {
            var that = $(this);
            $(this).summernote({
                fontNames: [
                    'Arial', '宋体', "新宋体", "仿宋", "微软雅黑", "楷体", "SimSun-ExtB", 'Arial Black', 'Comic Sans MS',
                    'Courier New', 'Merriweather'
                ],
                disableDragAndDrop: true,
                dialogsInBody: true,
                shortcuts: false,
                height: that.data("height"),
                minHeight: null,
                maxHeight: null,
                callbacks: {
                    onChange: function () {
                        that.val(that.summernote('code'));
                    },
                    onImageUpload: function (files) {
                        __sendFile(that, files, that.data("uploadurl"));
                    }
                },
                lang: 'zh-CN'
            });

            $(this).summernote('code', $(this).val());
        });
    }

    var textWithButton = function (collection) {
        $(collection)
            .find('.textwithbutton')
            .find(":text")
            .keydown(function (event) {
                if (event.which === 13) {
                    $(this).parents(".textwithbutton").find("button").first().trigger("click");
                }
            });
    }

    var tableEvent = function (collection) {
        var table;

        if ($(collection).is("table.jqtable")) {
            table = $(collection);
        } else {
            table = $(collection).find("table.jqtable");
        }

        //加载其他特殊功能
        $(table).each(function () {
            if ($(this).is("[webui-ignore]")) {
                return;
            }

            var leftFixedCount = 0;
            var rightFixedCount = 0;

            leftFixedCount = parseIntEx($(this).data("leftfixed"), 0);
            rightFixedCount = parseIntEx($(this).data("rightfixed"), 0);
            var scrollY = parseIntEx($(this).data("scrolly"), 0);
            var useKeyboard = $(this).data("keyboard") == "true";

            $(this).closest(".ibox-content").css("overflow-x", "hidden");

            var colWidthArgs = [];

            $(this).find("th")
                .each(function (index, element) {
                    if ($(this)) {
                        if (typeof ($(this).attr("style")) != "undefined" && $(this).attr("style").indexOf("width") >= 0) { //该列已设置宽度
                            var styleStr=$(this).attr("style");
                            
                            var styleindex=styleStr.indexOf('width:') + 6; 
                            var nextIndex= styleStr.indexOf(';',styleindex); 
                            

                            colWidthArgs.push({
                                "width": styleStr.substr(styleindex, nextIndex-styleindex),
                                "targets": index
                            });
                        }
                    }
                });

            var opt = {
                //scrollY: scrollY + 'px', // "300px",
                searching: false,
                ordering: false,
                info: false,
                footer: false,
                deferRender: false,
                scrollX: true,
                scrollCollapse: true,
                scrollY: false,
                autoWidth: true,
                //bAutoWidth: false,
                //responsive: true,
                //scroller: true,
                keys: useKeyboard,
                select: true,
                paging: false,
                //responsive: true,
                "sDom": '<"top">rt<"bottom"ifp><"clear">',
                "language": {
                    "emptyTable": "暂无数据"
                }
                //"bProcessing": true
            };

            if (leftFixedCount > 0 || rightFixedCount > 0) {
                opt["fixedColumns"] = {
                    heightMatch: "auto"
                };

                // if(leftFixedCount<=0){
                //     if(indexCol>=0){
                //         leftFixedCount=1;
                //     }
                    
                // }

                //if (leftFixedCount>0) {
                opt["fixedColumns"]["leftColumns"] = leftFixedCount;
                //}

                //if (rightFixedCount>0) {
                opt["fixedColumns"]["rightColumns"] = rightFixedCount;
                //}
            }


            if (scrollY > 0) {
                opt["scrollY"] = scrollY + 'px';
            }

            if (colWidthArgs.length > 0) {
                opt["columnDefs"] = colWidthArgs;
            }

            if (useKeyboard) {
                opt.select = {
                    style: 'single'
                }
            }

            var jqTable;

            try {

                jqTable = $(this).DataTable(opt).draw();;
                
                $(this).data("jquerydatatable", jqTable);

                $(this).data("leftFixedCount",leftFixedCount);
                //jqTable.wrap('');
            } catch (e) {
                return;
            }

            if (scrollY > 0) {
                $(this).parents(".dataTables_scrollBody").css("min-height", scrollY);

            }

            if (leftFixedCount <= 0 && rightFixedCount <= 0) {
                $(this).parents(".dataTables_wrapper").find(".dataTables_scrollHeadInner").css("width", "100%");
            }

            var jqtableWrapper=$(this).closest(".DTFC_ScrollWrapper");

            $(this).closest(".ibox-content").css("padding-bottom", "10px");

            $(jqtableWrapper).find('.dropdown-toggle').dropdown();

            var tableWrapper = $(this).closest(".dataTables_wrapper");

            tableWrapper.find(".DTFC_RightBodyLiner,DTFC_LeftBodyLiner").css("overflow-y", "hidden");

            var headerCells = $(this).closest(".dataTables_wrapper").find(".dataTables_scrollHead th");
            var body = $(this).closest(".DTFC_ScrollWrapper,.dataTables_scroll");

            var index = $.indefOfElement(headerCells, ".selectcol");

            if (index >= 0) {
                var checkboxCell = $(headerCells[index]);
                
                checkboxCell.find(":checkbox").change(function () {
                    if ($(this).is(":checked")) {
                        body.find("tr").each(function() {
                            //$($(this).find("td")[index]).find(":checkbox").attr("checked", "checked").trigger("change");
                            var checkbox = $($(this).find("td")[index]).find(".layui-form-checkbox");
                            if (!checkbox.is(".layui-form-checked")) {
                                checkbox.click();
                            }
                        });
                    } else {
                        body.find("tr").each(function() {
                            var checkbox = $($(this).find("td")[index]).find(".layui-form-checkbox");
                            if (checkbox.is(".layui-form-checked")) {
                                checkbox.click();
                            }
                        });
                    }
                });
            }


            $(this).find("td a.delrow").each(function() {

                $(this).click(function() {
                    var that = $(this);
                    WebUIJS.Confirm("是否删除该行?",
                        {
                            yes: function() {
                                jqTable.row($(that).closest("tr")).remove()
                                //.remove();
                                jqTable.draw();
                            }
                        });
                });
            });

            var wrapper = $(this).closest(".tablewrapper").removeClass("box");

            wrapper.find(".overlay").remove();
            //}

            //jqTable.columns.adjust().draw();
        });

    }

    var webuitable = function (collection) {
        var table=$(collection);

        if (!table.is("table")) {
            table = table.find("table");
        }

        if (table.length <= 0) {
            return;
        }

        table.each(function () {
            var $this = $(this);

            if (!$this.is(".webui_table")) {
                return;
            }

            if ($this.is(".wraped")) {
                return;
            }

            var scrollY = parseIntEx($this.data("scrolly"), 0);

            $this.simpleTable({
                leftFloatCol: parseIntEx($this.data("leftfixed"), 0),
                rightFloatCol: parseIntEx($this.data("rightfixed"), 0),
                scrollY: scrollY > 0,
                scrollHeight: scrollY
            }).on("webui_table.refresh",
                function () {
                    WebUIJS.RefreshEvent($this.closest(".webui_table_wrapper").find(".webui_table_float_left table,.webui_table_float_right table"));
                });

            
            
            //WebUIJS.RefreshEvent($this.closest(".webui_table_wrapper").find(".webui_table_float_left table,.webui_table_float_right table"));
        });

    }

    var tabContainer = function (collection) {
        if($(collection).is(".nav-tabs-custom")){
            collection=$(collection);
        }
        else{
            collection = $(collection).find(".nav-tabs-custom");
        }

        collection.each(function(){
            var container=$(this);

            // container.find(".tab-pane").each(function(){
            //     var pane=$(this);

            //     var tableWrapper=$(pane).find(".tablewrapper table");

            //     console.log(tableWrapper.outerHeight(true))
            // })

            container.find('a[data-toggle="tab"]').each(function () {
                var that = $(this);
    
                $(this).on('shown.bs.tab',
                    function (e) {

                        //$($.fn.dataTable.tables(true)).DataTable().columns.adjust();
                        

                        var tab = $(e.target);
                        var contentId = tab.attr("href");
    
                        //var jqTable = $(".dataTables_scrollBody table").data("jquerydatatable");
    
                        //This check if the tab is active
                        if (tab.parent().hasClass('active')) {
                            var tables = $(contentId + ".active").find(".dataTables_scrollBody table");
    
                            tables.each(function () {
                                var jqTable = $(this).data("jquerydatatable");
                                //jqTable.fixedColumns().update().relayout();
                                jqTable.columns.adjust().draw();
                            });

                            $(contentId + ".active").find("table.webui_table").each(function () {
                                $(this).simpleTable().refresh();
                            });

                            var activeScript = tab.data("active");
    
                            if (activeScript) {
                                __callBackFuncOrStr(activeScript, [tab, contentId]);
                            }
                        } else {
                            var unactiveScript = tab.data("unactive");
    
                            if (unactiveScript) {
                                __callBackFuncOrStr(unactiveScript, [tab, contentId]);
                                //eval(unactiveScript);
                            }
    
                        }
                    });
            });
        })



    }

    var datetimeEditor = function (collection) {
        collection = $(collection);

        if (!collection.is(".datetimepicker")) {
            collection = collection.find(".datetimepicker");
        }

        layui.use('laydate', function () {
            var laydate = layui.laydate;

            $(collection).each(function() {
                var textbox = $(this).find(".input-group :text");
                var that = $(this);
                //var content=$(this).find(".querycontent");
                var height = $(this).data("height");

                if ($(this).is("[webui-ignore]") || $(this).data("disabled") == "True") {
                    return;
                }

                if (!height) {
                    height = 300;
                } else {
                    height = parseIntEx(height, 300);
                }

                var opt = {
                    height: height,
                    elem: $(textbox)[0], //指定元素
                    type: $(this).data("pickertype").toLowerCase(),
                    format: $(this).data("format"),
                    value: $(textbox).val(),
                    isInitValue: true,
                    eventElem: $(this).find(".datetimepickershow")[0],
                    closeStop: $(this).find(".datetimepickershow i")[0],
                    position: "abolute",
                    trigger: 'click',
                    change: function(value, date, endDate) {
                        //console.log("dfdfsdf");
                        textbox.val(value);
                    }
                }

                if ($(this).data("maxdt") && $(this).data("maxdt") != "") {
                    opt.max = $(this).data("maxdt");
                }

                if ($(this).data("mindt") && $(this).data("mindt") != "") {
                    opt.min = $(this).data("mindt");
                }

                //执行一个laydate实例
                laydate.render(opt);

            });
        });
    }

    var datetimeRangeEditor = function (collection) {
        collection = $(collection);

        if (!collection.is(".datetimerangepicker")) {
            collection = collection.find(".datetimerangepicker");
        }

        layui.use('laydate', function () {
            var laydate = layui.laydate;

            $(collection).each(function() {
                if ($(this).is("[webui-ignore]") ) {
                    return;
                }

                //if ($(this).is("[disabled]")) {
                //    $(this).removeAttr("disabled");
                //    return;
                //}

                var that = $(this);
                var startText = $(this).find('.input-group :text.startvalue');
                var endText = $(this).find('.input-group :text.endvalue');
                
                var startCtrl;
                var endCtrl;
                var placeholder = $(this).data("placeholder");
                var height = $(this).data("height");

                if (!placeholder) {
                    placeholder = "";
                }

                if (!height) {
                    height = 300;
                } else {
                    height = parseIntEx(height, 300);
                }

                var opt = {
                    height: height,
                    placeholder: placeholder,
                    //elem:$(startText)[0],//指定元素
                    type: $(this).data("pickertype").toLowerCase(),
                    format: $(this).data("format"),
                    //value:$(text).val(),
                    //isInitValue: true,
                    position: "abolute"
                }

                if ($(this).data("maxdt") && $(this).data("maxdt") != "") {
                    opt.max = $(this).data("maxdt");
                }

                if ($(this).data("mindt") && $(this).data("mindt") != "") {
                    opt.min = $(this).data("mindt");
                }

                var endOpt = {
                    elem: $(endText)[0],
                    value: $(endText).val(),
                    change: function (value, dates) {
                        $(endText).val(value);
                        startCtrl.config.max = {
                            year: dates.year,
                            month: dates.month - 1, //关键 
                            date: dates.date,
                            hours: 0,
                            minutes: 0,
                            seconds: 0
                        }
                    },
                    done: function (value, dates) {
                        if (startCtrl) {
                            startCtrl.config.max = {
                                year: dates.year,
                                month: dates.month - 1, //关键 
                                date: dates.date,
                                hours: 0,
                                minutes: 0,
                                seconds: 0
                            }
                        }
                        
                        var p = 0;
                    }
                }

                var startOpt = {
                    elem: $(startText)[0],
                    value: $(startText).val(),
                    change: function (value, dates) {
                        $(startText).val(value);
                        endCtrl.config.min = {
                            year: dates.year,
                            month: dates.month - 1, //关键
                            date: dates.date,
                            hours: 0,
                            minutes: 0,
                            seconds: 0
                        }
                    },
                    done: function (value, dates) {
                        if (endCtrl) {
                            endCtrl.config.min = {
                                year: dates.year,
                                month: dates.month - 1, //关键
                                date: dates.date,
                                hours: 0,
                                minutes: 0,
                                seconds: 0
                            }
                        }
                        

                        var p = 0;
                    }
                }

                //执行一个laydate实例



                if (that.data("startdisabled").toLowerCase()!='true') {
                    startCtrl = laydate.render($.extend({}, opt, startOpt));
                }
                //else {
                //    startText.removeAttr("disabled");
                //}

                if (that.data("enddisabled").toLowerCase() != 'true') {
                    endCtrl = laydate.render($.extend({}, opt, endOpt));
                }
                //else {
                //    endText.removeAttr("disabled");
                //}
                
            });
        });
    }

    var singleFileUploader = function (collection) {
        $(collection).find(".singlefileuploader").each(function() {
            var that = $(this);
            var uploadUrl = $(that).data("uploadurl");
            var name = $(that).data("name");
            //var file = $(that).find(":file");
            var btn = $(that).find("uploader button");
            var maxfilesize = parseIntEx($(that).data("maxfilesize"));
            var btnIcon = btn.html(); //存储原来的显示数据
            var isDisabled = $(that).data("disabled") == "True";
            var hidden = $(that).find("input[type=hidden]");
            var accept = $(that).data("accept");
            var file;

            if (!name) {
                name = "file";
            }

            var fileChanged = function(data) {
                if (this.files.length <= 0) {
                    return false;
                }

                if (maxfilesize > 0 && this.files[0].size > maxfilesize) {
                    WebUIJS.Alert("文件太大,不能上传");
                    return false;
                }

                var fileName = this.files[0].name;

                if (uploadUrl && uploadUrl != "") {
                    $(that).find(".filepath").val("(上传中.....)");
                    //isDisabled = true;
                    btn.attr("disabled", "disabled");
                    $(that).find(".filepath").val("(上传中.....)" + fileName);

                    __uploadFileToServer(this,
                        uploadUrl,
                        {
                            onProgree: function(value) {
                                btn.html(value.toFixed(1) + "%");
                            },
                            onSuccess: function(data) {
                                if (data.IsSuccess) {
                                    $(that).find(".filepath").val(data.ReturnData);

                                    if (!hidden || hidden.length<=0) {
                                        hidden = $("<input type=\"hidden\" name=\"" + name + "\" />");
                                        $(that).find(".control-content .row").append(hidden);
                                    }

                                    hidden.val(data.ReturnData).change();
                                } else {
                                    WebUIJS.Alert(data.Message);
                                }
                            },
                            onComplete: function() {
                                btn.removeAttr("disabled");
                                btn.html(btnIcon);
                                isDisabled = false;

                                $(file).remove();

                                file = $("<input type=\"file\" />");

                                file.change(fileChanged);

                                $(that).append(file);
                            },
                            onError: function(error) {
                                WebUIJS.Alert(error.message);
                                $(that).find(".filepath").val(fileName);
                            },
                            fieldName: name
                        });
                } else {
                    $(that).find(".filepath").val("(等待上传.....)");
                    $(that).find(".control-content .row").append(file);
                    hidden = $(that).find("input[type=hidden]").val('');
                }

                
            };

            

            $(that).find(".uploader button.uploaderbtn,.filepath").click(function() {
                if (!isDisabled) {
                    file = $("<input type='file' name='" + name + "' accept=\"" + accept +"\"/>");
                    file.change(fileChanged);
                    file.click();
                }

            });

            $(that).find(".uploader button.clearfile").click(function(e) {
                if (!isDisabled) {
                    file = $("#file_uploade");
                    file.after(file.clone());
                    file.remove();

                    file = $(that).find(":file");
                    $(that).find(".filepath").val("");
                    hidden.val("");
                }

                return false;

            });


        });
    }

    var singleImageFileUploader = function (collection) {
        $(collection).find(".singleImageFileUploader").each(function() {
            var that = $(this);
            var uploadUrl = $(this).data("uploadurl");
            var name = $(that).data("name");
            var image = $(that).find("img.uploadimage");
            //var file = $(that).find(":file");
            var isDisabled = $(that).data("disabled") == "True";
            var maxfilesize = parseIntEx($(that).data("maxfilesize"));
            var hidden = $(this).find("input[type=hidden]");
            var file;

            //_autoScaleImage(image,false);

            var fileChanged = function() {

                if (maxfilesize > 0 && this.files[0].size > maxfilesize) {
                    WebUIJS.Alert("文件太大,不能上传");
                    return false;
                }

                if (this.files.length<=0 || !this.files[0]) {
                    //WebUIJS.Alert("请选择文件");
                    return false;
                }
                
                try {
                    var reader = new FileReader();
                    reader.onload = function(evt) {
                        $(image).attr('src', evt.target.result);

                        //$(that).parents('.input-group').find('.data').val(null);
                    }
                    reader.readAsDataURL(this.files[0]);
                } catch (e) {
                    image.attr('src', $(this).val());
                    WebUIJS.Toast("加载图片错误:" + e.message, "error", 2);
                    //return;
                }

                if (uploadUrl && uploadUrl != "") {

                    __uploadFileToServer(this,
                        uploadUrl,
                        {
                            onSuccess: function (data) {
                                if (data.IsSuccess) {
                                    image.attr('src', data.ReturnData);

                                    if (!hidden || hidden.length <= 0) {
                                        hidden = $("<input type=\"hidden\" name=\"" + name + "\" />");
                                        $(that).append(hidden);
                                    }

                                    hidden.val(data.ReturnData).change();

                                    WebUIJS.Toast("图片上传完成", "success", 1);

                                    //$(file).remove();

                                    //file = $("<input type=\"file\" />");

                                    //file.change(fileChanged);

                                    //$(that).append(file);
                                } else {
                                    WebUIJS.Alert(data.Message);
                                }
                            },
                            fieldName: name
                        });
                } else {
                    $(that).find(".control-content .row").append(file);
                    hidden = $(that).find("input[type=hidden]").val('');
                }
            }

            //file.on("change", fileChanged);

            $(image).click(function() {
                if (!isDisabled) {
                    file = $("<input type='file' name='" + name + "' accept=\"image/*\"/>");
                    file.change(fileChanged);
                    file.click();
                }

            });
        });
    }

    var multifileuploader = function (collection) {
        $(collection).find(".multifileuploader").each(function() {
            var that = $(this);
            var tbody = $(this).find("table tbody");
            var uploadUrl = $(this).data("uploadurl");
            var name = $(this).data("name");
            var maxfilesize = parseIntEx($(that).data("maxfilesize"));

            $(that).find(".badge-del").each(function () {
                $(this).click(function () {
                    $(this).closest("tr").remove();
                });
            });

            $(this).find(".addfile").click(function() {
                var file = $('<input type="file" name="' + name + '"/>');

                file.change(function() {
                    if (this.files.length <= 0) {
                        return false;
                    }

                    if (maxfilesize > 0 && this.files[0].size > maxfilesize) {
                        WebUIJS.Alert("文件太大,不能上传");
                        return false;
                    }

                    var tr = $("<tr></tr>");

                    tr.append("<td class='filename' style='word-break:break-word;'>" + this.files[0].name + " </td>");
                    tr.append('<td><input type=\"hidden\" name=\"' +
                        name +
                        '\" /><div class="progress progress-xs progress-striped active"><div class="progress-bar progress-bar-success" style="width: 0%"></div></div></td>');
                    tr.append(
                        '<td><span class="badge bg-light-blue badge-status">等待上传</span><br/><span class="badge bg-red badge-del" style=\"cursor: pointer;\">删除</span></td>');
                    tr.append(file);
                    var progress = $(tr).find(".progress .progress-bar");
                    var statusBadge = $(tr).find(".badge-status");
                    var delBadge = $(tr).find(".badge-del");
                    var hidden = $(tr).find("input[type=hidden]");

                    tbody.append(tr);

                    delBadge.click(function(){
                        $(this).closest("tr").remove();
                    });

                    if (uploadUrl && uploadUrl != "") {

                        __uploadFileToServer(this,
                            uploadUrl,
                            {
                                onProgree: function(value) {
                                    $(progress).css("width", value + "%");
                                    $(statusBadge).text(value.toFixed(1) + "%");
                                },
                                onSuccess: function (data) {
                                    if (data.IsSuccess) {
                                        $(tr).find(".filename").text(data.ReturnData);
                                        $(tr).find(".url").text(data.ReturnData);
                                        $(hidden).val(data.ReturnData);
                                        statusBadge.text("上传完成");
                                    } else {
                                        $(tr).remove();
                                        WebUIJS.Alert(data.Message);
                                    }

                                    $(file).remove();
                                },
                                fieldName: name
                            });
                    }
                });

                file.click();
            });
        });
    }

    var multiimageuploader = function (collection) {
        var imageViewer = function (btn) {
            $(btn).click(function () {
                var img = $(btn).closest("tr").find("img");

                var src = img.attr("src");

                if (src && src != "") {
                    WebUIJS.ShowImageViewer(src);
                }
                
            });
        }

        var editImage = function (btn, maxFileSize, uploadUrl) {
            var that = (btn);
            $(btn).click(function () {
                var file = $('<input type="file" name="' + name + '" accept=\"image/*\"/>');

                file.change(function () {
                    if (this.files.length <= 0) {
                        return false;
                    }

                    if (maxFileSize > 0 && this.files[0].size > maxFileSize) {
                        WebUIJS.Alert("文件太大,不能上传");
                        return false;
                    }

                    var tr = $(that).closest("tr");

                    var progress = $(tr).find(".progress .progress-bar");
                    var statusBadge = $(tr).find(".badge-status");
                    var hidden = $(tr).find("input[type=hidden]");

                    var image = tr.find("img");


                    try {
                        var reader = new FileReader();
                        reader.onloadend = function (evt) {
                            $(image).attr('src', evt.target.result);
                        }

                        reader.onerror = function (e) {
                            WebUIJS.Toast("读取图片文件错误");
                        }

                        reader.readAsDataURL(this.files[0]);
                    } catch (e) {
                        WebUIJS.Toast("加载图片错误:" + e.message, "error", 2);
                    }

                    if (uploadUrl && uploadUrl !== "") {

                        __uploadFileToServer(this,
                            uploadUrl,
                            {
                                onProgree: function (value) {
                                    $(progress).css("width", value + "%");
                                    $(statusBadge).text(value.toFixed(1) + "%");
                                },
                                onSuccess: function (data) {
                                    if (data.IsSuccess) {
                                        $(image).attr("src", data.ReturnData);
                                        $(hidden).val(data.ReturnData);
                                        statusBadge.text("上传完成");
                                    } else {
                                        $(tr).remove();
                                        WebUIJS.Alert(data.Message);
                                    }
                                },
                                fieldName: name
                            });
                    } else {
                        tr.append(file);
                    }
                });

                file.click();
            });
        }

        var clearimage = function(btn) {
            var tr = $(this).closest("tr");
            tr.find("img").src("");
            tr.find("input[type=hidden]").value("");
        }

        $(collection).find(".multiimageuploadfield").each(function () {
            var that = $(this);
            var tbody = $(this).find("table tbody");
            var uploadUrl = $(this).data("uploadurl");
            var name = $(this).data("name");
            var maxfilesize = parseIntEx($(that).data("maxfilesize"));
            var maxcount = parseIntEx("maxcount", 0);
    

            $(this).find(".badge-view").each(function() {
                imageViewer($(this));
            });

            $(this).find(".badge-del").each(function () {
                $(this).click(function() {
                    $(this).closest("tr").remove();
                });
            });

            $(this).find(".badge-edit").each(function() {
                editImage(this, maxfilesize, uploadUrl);
            });

            $(this).find("img").each(function() {
                //_autoScaleImage($(this));
                $(this).attr("src", $(this).data("src"));
            });

            $(this).find(".addfile").click(function () {
                var file = $('<input type="file" name="' + name + '" accept=\"image/*\"/>');

                file.change(function () {
                    if (this.files.length <= 0) {
                        return false;
                    }

                    if (maxfilesize > 0 && this.files[0].size > maxfilesize) {
                        WebUIJS.Alert("文件太大,不能上传");
                        return false;
                    }

                    var tr = $("<tr></tr>");

                    tr.append("<td class='filename'><img/></td>");
                    tr.append('<td style=\"vertical-align: middle;\"><input type=\"hidden\" name=\"' +
                        name +
                        '\" /><div class="progress progress-xs progress-striped active"><div class="progress-bar progress-bar-success" style="width: 0%"></div></div></td>');

                    var optTd = $("<td style=\"vertical-align: middle;\"></td>");

                    optTd.append('<span class="badge bg-green badge-view" style=\"cursor: pointer;\">查看图片</span><br/><span class="badge bg-red badge-edit" style=\"cursor: pointer;\">修改</span><br/><span class="badge bg-light-blue badge-status" style=\"cursor: pointer;\">等待上传</span><br/>');

                    if (maxcount <= 0) {
                        optTd.append('<span class="badge bg-red badge-del" style=\"cursor: pointer;\">删除</span></td>')
                    } else {
                        optTd.append('<span class="badge bg-red badge-clear" style=\"cursor: pointer;\">清除</span></td>')
                    }
                    
                    tr.append('</td>');

                    var progress = $(tr).find(".progress .progress-bar");
                    var statusBadge = $(tr).find(".badge-status");
                    var delBadge = $(tr).find(".badge-del");
                    var editimg = $(tr).find(".badge-edit");
                    var clearimg = $(tr).find(".badge-clear");
                    var viewimg = $(tr).find(".badge-view");
                    var hidden = $(tr).find("input[type=hidden]");

                    tbody.append(tr);

                    delBadge.click(function() {
                        $(this).closest("tr").remove();
                    });
                    clearimg.click(function() {
                        clearimage(this);
                    });
                    editimg.click(function() {
                        editImage(this);
                    });

                    var image = tr.find("img");

                    //_autoScaleImage(image);

                    imageViewer(viewimg);

                    try {
                        var reader = new FileReader();
                        reader.onloadend = function (evt) {
                            $(image).attr('src', evt.target.result);
                        }
           
                        reader.onerror = function(e) {
                            WebUIJS.Toast("读取图片文件错误");
                        }
                 
                        reader.readAsDataURL(this.files[0]);
                    } catch (e) {
                        WebUIJS.Toast("加载图片错误:" + e.message, "error", 2);
                    }

                    if (uploadUrl && uploadUrl !== "") {

                        __uploadFileToServer(this,
                            uploadUrl,
                            {
                                onProgree: function(value) {
                                    $(progress).css("width", value + "%");
                                    $(statusBadge).text(value.toFixed(1) + "%");
                                },
                                onSuccess: function (data) {
                                    if (data.IsSuccess) {
                                        $(image).attr("src", data.ReturnData);
                                        $(hidden).val(data.ReturnData);
                                        statusBadge.text("上传完成");
                                    } else {
                                        $(tr).remove();
                                        WebUIJS.Alert(data.Message);
                                    }

                                    //badge.removeClass("bg-light-blue").addClass("bg-red").text("删除").click(function() {
                                    //    $(this).closest("tr").remove();
                                    //});
                                    
                                    //$(file).remove();
                                },
                                fieldName: name
                            });
                    } else {
                        tr.append(file);
                    }
                });

                file.click();
            });
        });
    }

    var multiimageuploader2 = function (collection) {
        var uploader;

        if ($(collection).is(".webui-form_multi-image-uploader")) {
            uploader = $(collection);
        } else {
            uploader = $(collection).find(".webui-form_multi-image-uploader");
        }

        uploader.each(function () {

            var $this = $(this);

            $(this).find(".multi-image-uploader").multiImageUploader({
                uploadUrl: $this.data("uploadurl"),
                name: $this.data("name"),
                maxFileSize: parseIntEx($this.data("maxfilesize"),0),
                disabled: $this.data("disabled")=="True",
                width: parseIntEx($this.data("width"), 0),
                height: parseIntEx($this.data("height"), 0),
                 colSize: parseIntEx($this.data("colsize"), 0),
                //maxcou:  parseIntEx($this.data("maxcount"),0)
            });  
        });
    }

    var citypicker = function (collection) {
        var cityPickers = $(collection).find(".citypicker");

        var configCityPciker = function () {
            var that = $(this);

            

            var citytextbox = $(this).find(".citypickertextbox");

            if (!isEmpty(citytextbox.attr("readonly"))) {
                return;
            }


            var level = $(that).data("level");
            var hidProvince = $(that).find(".provincecode");
            var hidCity = $(that).find(".citycode");
            var hidDistrict = $(that).find(".districtcode");

            if (!level || level == "" || level == "all") {
                level = "district";
            }

            var value = $(citytextbox).val().split('/');



            var province = "";
            var city = "";
            var district = "";

            if (value.length >= 3) {
                province = value[0];
                city = value[1];
                district = value[2];
            } else if (value.length >= 2) {
                province = value[0];
                city = value[1];
            } else if (value.length >= 1) {
                province = value[0];
            }

            $(citytextbox).on("cp:updated", function () {
                $(that).find("span.select-item").each(function () {
                    var level1 = $(this).data("count");
                    var code = $(this).data("code");

                    if (level1 == "province") {
                        hidProvince.val(code);
                    } else if (level1 == "city") {
                        hidCity.val(code);
                    } else if (level1 == "district") {
                        hidDistrict.val(code);
                    }
                })
            })

            $(citytextbox).change(function () {
                $(that).find("span.select-item").each(function () {
                    console.log("sdfsdfd");
                })
            })

            $(citytextbox).citypicker({
                responsive: true,
                placeholder: citytextbox.attr("placeholder"),
                level: level,
                province: province,
                city: city,
                district: district
            })

            if (value && value != "") {
                $(citytextbox).data("citypicker").feedVal(true);
            }

        };

        if (cityPickers.length > 0) {
            if (!$(this).citypicker) {
                $("<link/>", {
                    rel: "stylesheet",
                    type: "text/css",
                    href: WebUIJS.ResourceUrl + "/Content/js/citypicker/css/city-picker.css"
                }).appendTo("head");

                $.getScript(WebUIJS.ResourceUrl + "/Content/js/citypicker/js/city-picker.data.min.js", function () {
                    $.getScript(WebUIJS.ResourceUrl + "/Content/js/citypicker/js/city-picker.min.js", function () {
                        cityPickers.each(configCityPciker);
                    })
                });
            } else {
                cityPickers.each(configCityPciker);
            }
        }


    }

    var pager = function (collection) {
        collection = $(collection).find(".pagination:not(.ajaxpager)");

        $(collection).each(function() {
            var inputItem = $(this).prev().find(".pagerinput:not(.ajaxpager)");
            var pager = $(this);
            var urlTemplate = pager.data("url-format");

            $(inputItem).keydown(function (event) {
                if (event.keyCode == 13) {
                    var value = $(this).val();
                    if (parseIntEx(value, 0) <= 0) {
                        return;
                    }

                    WebUIJS.GoTo(urlTemplate.replace("__pageIndex__", value), pager);
                }
            });
        });
    }

    var ajaxPager = function(collection) {
        $(collection).find(".ajaxpager").each(function() {
            var pager = $(this);
            var pagerActionUrl = $(pager).data("actionurl");
            var pageKey = $(pager).data("pageParameter");


            var updateEl = pager.data("updateelementid");

            $(pager).find("a[href]").each(function() {
                var a = $(this);

                var href = a.attr("href");

                if (href === "" || href === "#") {
                    return;
                }
                
                //如果有自定义数据获取Url,则使用自定义的
                if (!isEmpty(pagerActionUrl)) {
                    var newUrl =new URI(href);

                    var pageIndex = new URI(href).query(true)[pageKey];

                    var gotoUrl = new URI(pagerActionUrl);
                    gotoUrl.setSearch(pageKey, pageIndex);

                    href = gotoUrl.toString();
                }

                a.data("ajaxurl", href);
                
                a.click(function (e) {
                    e.stopPropagation();

                    $.ajax({
                        async: true,
                        //data: data,
                        type: "get",
                        url: $(this).data("ajaxurl"),
                        dataType: "html",
                        contentType: "",
                        success: function(responseText, textStatus, jqXHR) {

                            var targetEl = $('#' + updateEl);
                            targetEl.empty();

                            var item = $(responseText).is("#" + updateEl) ? $(responseText) : $(responseText).find("#" + updateEl);
                            
                            if (item.length > 0) {
                                targetEl.replaceWith(item);
                            } else {
                                targetEl.html(responseText);
                            }
                            
                            var newItem = $('#' + updateEl);

                            WebUIJS.RefreshEvent(newItem);

                            var layer = newItem.closest(".layui-layer");
                            if (layer.length > 0) {
                                layer.trigger("refresh");
                            }
                        },
                        beforeSend: function(xhr) {
                            WebUIJS.Loading();
                        },
                        complete: function(jqXHR, textStatus) {
                            $(pager).data("disabled", null);
                            
                            WebUIJS.CloseLoading();
                        }
                    });

                    return false;
                });
            });

            $(pager).parent().find(".pagerinput").each(function() {
                var txt = $(this);
                
                $(this).keyup(function(event) {
                    var keycode = (event.keyCode ? event.keyCode : event.which);
                    if (keycode !== 13) {
                        return;
                    }

                    var pageIndex = parseIntEx($(txt).val(), 1);

                    var href = "";

                    //如果有自定义数据获取Url,则使用自定义的
                    if (!isEmpty(pagerActionUrl)) {
                        
                        var gotoUrl = new URI(pagerActionUrl);
                        gotoUrl.setSearch(pageKey, pageIndex);

                        href = gotoUrl.toString();
                    } else {
                        href = $('.ajaxpager').data("urlFormat").replace("__pageIndex__", pageIndex);
                    }

                    event.stopPropagation();

                    $.ajax({
                        async: true,
                        //data: data,
                        type: "get",
                        url: href,
                        dataType: "html",
                        success: function(responseText, textStatus, jqXHR) {

                            var targetEl = $('#' + updateEl);
                            targetEl.empty();

                            var item = $(responseText).is("#" + updateEl) ? $(responseText) : $(responseText).find("#" + updateEl);

                            if (item.length > 0) {
                                targetEl.replaceWith(item);
                            } else {
                                targetEl.html(responseText);
                            }

                            var newItem = $('#' + updateEl);

                            WebUIJS.RefreshEvent(newItem);

                            var layer = newItem.closest(".layui-layer");
                            if (layer.length > 0) {
                                layer.trigger("refresh");
                            }
                        },
                        beforeSend: function(xhr) {
                            WebUIJS.Loading();
                        },
                        complete: function(jqXHR, textStatus) {
                            $(pager).data("disabled", null);

                            WebUIJS.CloseLoading();
                        }
                    });

                    return false;
                });
            });
        });
    };

    var summernote=function(collection){
        collection=$(collection);

        if (!collection.is(".summernoteeditor")){
            collection = $(collection).find(".summernoteeditor");
        }

        collection.each(function() {
            var that = $(this);
            var textarea = $(this).find("textarea");

            $(textarea).summernote({
                fontNames: [
                    'Arial', '宋体', "新宋体", "仿宋", "微软雅黑", "楷体", "SimSun-ExtB", 'Arial Black', 'Comic Sans MS',
                    'Courier New', 'Merriweather'
                ],
                disableDragAndDrop: true,
                dialogsInBody: true,
                shortcuts: false,
                height: that.data("height"),
                placeholder: that.data("placeholder"),
                minHeight: null,
                maxHeight: null,
                lang: 'zh-CN',
                callbacks: {
                    onChange: function() {
                        textarea.val(textarea.summernote('code'));
                    },
                    onImageUpload: function(files) {
                        __uploadFileToServer(files,
                            that.data("uploadurl"),
                            {
                                'sender': that,
                                onSuccess: function(data) {
                                    //var img = $("<img width='100%' src='" + data.ReturnData + "' />");

                                    var img = document.createElement('img');
                                    img.src = data.ReturnData;
                                    $(img).css("width","100%");
                                    

                                    textarea.summernote('insertNode', img);
                                }
                            }
                        );
                    }
                }
            });

            $(textarea).summernote('code', $(textarea).find("textarea").val());

            $(that).find(".note-btn.dropdown-toggle").each(function() {
                $(this).click(function () {
                    $($(this).closest(".note-btn-group")).trigger("shown.bs.dropdown");
                    return false;
                });
            });

            if ($(textarea).is("[readonly]")) {
                $(textarea).summernote('disable');
            }
        });


    }

    var images = function(collection) {
        $(collection).find("img").each(function() {
            var img = $(this);

            img.on("error",
                function() {
                    if (img.height() >= img.width()) {
                        $(this).attr("src", WebUIJS.ResourceUrl + "/Content/images/picerror_80_80.jpg");
                    } else {
                        $(this).attr("src", WebUIJS.ResourceUrl + "/Content/images/picerror_200_100.jpg");
                    }

                });
        });
    }

    var tree = function(collection) {
        if (!collection.is(".webui_treeview")) {
            collection = collection.find(".webui_treeview");
        }

        collection.each(function() {
            var $that = $(this);

            if ($(this).find(".treeview_treeul").length <= 0) {
                return;
            }

            var onChangedScript=$that.data("changedcallback");
            var mutilselect=$that.data("mutilselect")=="True";
            var enablePlugin=[];

            if(mutilselect){
                enablePlugin.push("checkbox");
            }

            var jstree = $that.find(".treeview_tree_wrapper").jstree({
                "core": {
                    "themes": {
                        "icons": false
                    },
                    mutilselect:mutilselect,
                    dblclick_toggle: false,
                    expand_selected_onload: true
                },
                "plugins": enablePlugin

            }).jstree("open_all")
            .on("changed.jstree", function (e, node, action, selected) {
                if(!isEmpty(onChangedScript)){
                    var valueArray = [];

                    for (var index = 0; index < node.selected.length; index++) {
                        var liNode = node.instance.get_node(node.selected[index]);
                        var liAttr = liNode.li_attr;
                        if (!liAttr || !liAttr.hasOwnProperty("data-value")) {
                            continue;
                        }

                        valueArray.push(liAttr["data-value"]);
                    }

                    __callBackFuncOrStr(onChangedScript,node,[valueArray])
                }
                }).on("activate_node.jstree", function (e, event) {
                 
                    var itemOnClick=event.node.li_attr["data-onclick"];
                    if (!isEmpty(itemOnClick)) {
                        var clickNodeValue = event.node.li_attr["data-value"];
                        __callBackFuncOrStr(itemOnClick, event, [clickNodeValue]);
                    }
                }).on("ready.jstree", function (event) {
                    var tree = $(this).jstree(true);
                    tree.open_all();
                });

            $that.data("jstree", jstree);

            if (mutilselect){
                $that.click(function (e) {
                    e.stopPropagation();
                });
            }
        });
    }

    var treeSelectorField = function(collection)
    {
        if (!collection.is(".webui-form_treeviewselectorfield")) {
            collection = collection.find(".webui-form_treeviewselectorfield");
        }

        collection.each(function () {
 

            var $that = $(this);

            $that.find(".form-control").click(function (e) {
                $(this).parent().find("button").dropdown('toggle');
                e.stopPropagation();
            });

            if ($(this).find(".jstree-node").length <= 0) {
                $(this).find(".dropdown-treeview-menu-container").css("min-height", "0px");

                return;
            }

            var jstree = $that.find(".webui_treeview").data("jstree");

            jstree.on("changed.jstree",
                function(e, node, action, selected) {
                    var valueArray = [];
                    var textArray = [];
                    var field = $(e.currentTarget).closest(".webui-form_treeviewselectorfield");

                    for (var index = 0; index < node.selected.length; index++) {
                        var liNode = node.instance.get_node(node.selected[index]);

                        var liAttr = liNode.li_attr;

                        if (!liAttr || !liAttr.hasOwnProperty("data-value")) {
                            continue;
                        }

                        valueArray.push(liAttr["data-value"]);
                        textArray.push(liNode.text.replace('\n',''));
                    }

                    field.find("input[type=hidden]").val(valueArray.join());
                    field.find(".form-control .title")
                        .text(textArray.join());

                });
        });
    }



    var lineChart = function (collection) {
        if (!$(collection).is(".chartjsbox")) {
            collection = $(collection).find(".chartjsbox")
        }

        $(collection).each(function () {
            var canvas = $(this).find("canvas")[0].getContext('2d');
            var yAxesTitle = $(this).data("yaxestitle");
            var xAxesTitle = $(this).data("xaxestitle");



        })

    }



    layui.use(['form', 'layer'], function () {
        var form = layui.form;

        form.render();

        layer = layui.layer;
    });

    
    panelBox(el);
    ajaxForm(el);
    images(el);
    datetimeEditor(el);
    datetimeRangeEditor(el);
    singleFileUploader(el);
    singleImageFileUploader(el);
    multifileuploader(el);
    multiimageuploader(el);
    multiimageuploader2(el);
    summernote(el);
    tree(el);
    pager(el);
    ajaxPager(el);
    text(el);
    citypicker(el);
    button(el);
    selector(el);
    textEditor(el);
    textWithButton(el);
    tabContainer(el);
    tableEvent(el);
    webuitable(el);
    treeSelectorField(el);
    querybox(el);

    if (typeof window.setupValidaor != "undefined") {
        window.setupValidaor(el);
    }

    if (onsuccess) {
        onsuccess();
    }
}


WebUIJS.SetActiveMenuKey = function (menuKey) {
    if (!menuKey || menuKey == "") {
        return;
    }

    var mainMenu = $(".webui_mainmenu");

    mainMenu.find("li.menu-open,li.active").removeClass("menu-open").removeClass("active");
    mainMenu.find("ul").each(function () {
        $(this).css("display", "none");
    });

    var link = mainMenu.find("a[data-menukey=" + menuKey + "]");

    if (link && link.length > 0) {
        link = $(link[0]);

        link.parents("ul,li").each(function () {
            var item = $(this);

            if (item.is("ul.sidebar-menu")) {
                return false;
            }

            if (item.is("ul")) {
                item.css("display", "block");
            } else if ($(this).is("li")) {
                item.addClass("active");

                if (item.is(".treeview")) {
                    item.addClass("menu-open")
                }
            }

        })
    }
}


function __getFuncID(func) {
    var id = "callback_" + Date.parse(new Date());

    funcs[id] = func;

    return id;
}

function __callFuncByID(id, args) {
    funcs[id](args);
}

var randomIndex = 0;

function __getRandomID() {
    randomIndex += 1;
    //var newRandom = randomIndex;
    return "randomID_" + randomIndex;
}

function __setRandomData(idOrValue, value) {
    if (typeof value == "undefined") {
        value = idOrValue;

        idOrValue = __getRandomID();
    }

    randomData[idOrValue.toString()] = value;

    return idOrValue;
}

function __getRandomData(id) {
    return randomData[id.toString()];
}

/*
 * 数据结构
 * {
 *    message: //消息名称  CallFunction：回调指定函数
 *    Args:{},  //参数
 *    FuncName:string  //调用的函数名称         
 * }
 * 
 */
function __onMessage(event) {
    var data = JSON.parse(event.data);
    var source = event.source;

    if (data == null) {
        return;
    }

    var funcName = data.FuncName;

    if (funcName === undefined) {
        var messageHandlers = eventHandlers["system.message"];

        if (messageHandlers.length > 0) {
            for (var j = 0; j < messageHandlers.length; j++) {
                var handler = messageHandlers[i];

                handler(event.data);
            }
        }
    }

    var args = data.Args;
    var callbackArgs = data.Callback;

    //优先判断是不是系统消息
    if ("undefined" != typeof __systemMessageHandler && __systemMessageHandler(source, funcName, args, callbackArgs)) {
        return;
    }

    var func = funcs[funcName];
    if (func == null) {
        console.log("不存在指定的函数名" + funcName);
        return;
    }

    var argsLst = [];

    if (args != null) {
        var k = 0;
        for (var i in args) {
            argsLst[k] = args[i];
            k++;
        }
    }

    func.apply(this, source, argsLst, callbackArgs);
}

var webcamWidth = 0;
var webcamHeight = 0;


function __showWebCam(successCallback, faildCallback) {
    var showCam = function () {
        layer.open({
            btnAlign: 'c',
            content: '<div id="my_camera"></div>',
            btn: ['拍摄', '取消'],
            yes: function (index, layero) {
                //确定拍摄
                Webcam.snap(function (data_uri) {
                    Webcam.reset();
                    successCallback(data_uri, webcamWidth, webcamHeight);
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    // display results in page
                    //document.getElementById('results').innerHTML =
                    //    '<h2>Here is your large image:</h2>' +
                    //    '<img src="' + data_uri + '"/>';
                });


            },
            btn2: function (index, layero) {
                //取消

                layer.close(index); //如果设定了yes回调，需进行手工关闭
                faildCallback();
                Webcam.reset();
            },
            cancel: function (layero, index) {
                //右上角关闭回调

                layer.close(index); //如果设定了yes回调，需进行手工关闭
                faildCallback();
                Webcam.reset();

            },
            success: function (layero, index) {
                if (webcamWidth <= 0) {
                    Webcam.set({
                        width: 320,
                        height: 240,
                        //dest_width: 1280,
                        //dest_height: 720,
                        image_format: 'jpeg',
                        jpeg_quality: 90
                    });

                    Webcam.attach('#my_camera');

                    var video = $(layero).find("video")[0];

                    video.addEventListener('loadedmetadata',
                        function () {
                            webcamWidth = video.videoWidth;
                            webcamHeight = video.videoHeight;

                            Webcam.reset();

                            Webcam.set({
                                width: 320,
                                height: 240,
                                dest_width: webcamWidth,
                                dest_height: webcamHeight,
                                image_format: 'jpeg',
                                jpeg_quality: 90
                            });

                            Webcam.attach('#my_camera');
                        });
                } else {
                    Webcam.set({
                        width: 320,
                        height: 240,
                        dest_width: webcamWidth,
                        dest_height: webcamHeight,
                        image_format: 'jpeg',
                        jpeg_quality: 90
                    });

                    Webcam.attach('#my_camera');
                }
            }

        });
    }


    if (!Webcam) {
        if (($.browser.msie && (parseFloat($.browser.version) >= 9.0)) || !$.browser.msie) {
            WebUIJS.Toast("正在加载WebCam脚本,请稍等.....", success, 1)
            WebUIJS.Loading();

            $.getScript("http://ylfile.b0.upaiyun.com/Inspinia/Content/js/plugins/webcam/webcam.min.js", function () {
                WebUIJS.CloseLoading();
                showCam();
            });
        } else {
            WebUIJS.Alert("当前浏览器不支持WebCam");
        }

    } else {
        showCam();
    }


}


function __autoTabContentWidth() {
    $(".nav-tabs-custom.tabs-left").each(function () {
        var tabWidth = $(this).outerWidth();
        var navWidth = $(this).children(".nav-tabs").outerWidth();
        $(this).children(".tab-content").outerWidth(tabWidth - navWidth);
    });
}


var resizeTimeout;
var pushMenuTimeout;

$(document).ready(function() {
    layui.use('form',
        function() {
            var form = layui.form;

            form.on('checkbox',
                function(data) {
                    $(data.elem).trigger("change");
                });

            form.on('radio',
                function(data) {
                    $(data.elem).trigger("change");

                });

            form.on('select',
                function(data) {    
                    $(data.elem).trigger("change");
 
                });

            form.on('switch',
                function(data) {
                    $(data.elem).trigger("change");

                });
            form.render();


        });

    layui.use('layer',
        function() {
            layer = layui.layer;

        });
    
    $(".square").each(function() {
        //
        $(this).height($(this).width());
    });

    __autoTabContentWidth();

    $(window).resize(function() {
        $(".square").each(function() {
            $(this).height($(this).width());
        });

        __autoTabContentWidth();

        $(".webui_table").each(function() {
            $(this).simpleTable().refresh()
        });

        //if (resizeTimeout) {
        //    clearTimeout(window.refresh_size);
        //}

        //修复窗体大小变化时,自动缩放
        //resizeTimeout = setTimeout(function() {
        //        $('.dataTables_scrollBody table').each(function() {
        //            var odata = $(this).data("jquerydatatable");

        //            //var leftFixedCount=$(this).data("leftFixedCount");

        //            odata.columns.adjust().draw();
        //        });
        //    },
        //    250);
    });

    if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', __onMessage, false);
    } else if (typeof window.attachEvent != 'undefined') {
        //for ie
        window.attachEvent('onmessage', __onMessage);
    }

    $(".sidebar-toggle").click(function () {
        if (pushMenuTimeout) {
            clearTimeout(pushMenuTimeout);
        }

        pushMenuTimeout = setTimeout(function () {
            $(window).resize();
        }, 300);
    });

    $(window).on("unload",
        function() {
            WebUIJS.Loading();
        });
});

/*===========公用函数================*/

function isArray(obj) {
    return (typeof obj == 'object') && obj.constructor == Array;
}

function isString(str) {
    return (typeof str == 'string') && str.constructor == String;
}

function isNumber(obj) {
    return (typeof obj == 'number') && obj.constructor == Number;
}

function isDate(obj) {
    return (typeof obj == 'object') && obj.constructor == Date;
}

function isFunction(obj) {
    return ("undefined" != typeof obj && obj != null && typeof obj == 'function') && obj.constructor == Function;
}

function isObject(obj) {
    if ("undefined" == typeof obj || obj == null) {
        return false;
    }

    return (typeof obj == 'object');
}


//判断是否为空 
function isEmpty(str) {
    if ("undefined" == typeof str || str == null || $.trim(str) === "") {
        return true;
    } else {
        return false;
    }
}

var srcIsFunction = $.isFunction;
$.isFunction = function (obj) {
    if (typeof obj != "undefined" && obj != null && srcIsFunction(obj)) {
        return true;
    } else {
        return false;
    }
}

var userAgent = navigator.userAgent.toLowerCase();
// Figure out what browser is being used 
jQuery.browser = {
    version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
    safari: /webkit/.test(userAgent),
    opera: /opera/.test(userAgent),
    msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
    mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
};


String.prototype.toStringEx = function (defaultValue) {
    if (this == null) {
        return defaultValue;
    }

    var formatted = this;

    if (arguments.length === 1 && isObject(arguments)) {
        var args = arguments[0];
        for (var arg in args) {
            formatted = formatted.replace("{" + arg + "}", args[arg]);
        }
    } else {
        for (var arg in arguments) {
            formatted = formatted.replace("{" + arg + "}", arguments[arg]);
        }
    }


    return formatted;
};

function toStringEx (str, defaultValue) {

    if (str==null) {
        return defaultValue;
    }

    if (typeof str == "undefined") {
        return defaultValue;
    }

    var formatted = str;

    if (arguments.length === 1 && isObject(arguments)) {
        var args = arguments[0];
        for (var arg in args) {
            formatted = formatted.replace("{" + arg + "}", args[arg]);
        }
    } else {
        for (var arg in arguments) {
            formatted = formatted.replace("{" + arg + "}", arguments[arg]);
        }
    }


    return formatted;
};

function getPropertyEx(obj, propName, defaultValue) {
    if (obj == null) {
        return defaultValue;
    }

    if (isObject(obj) && obj.hasOwnProperty(propName)) {
        return obj[propName];
    } else {
        return defaultValue;
    }
}

//根据配置,使用get或post的方式,获取html数据,内部使用
function __httpGetOrPostDataByHtml(url, data, onsuccess, onError, httpMethod, isShowLoading, sender) {
    if (typeof httpMethod == "undefined") {
        httpMethod = "get";
    }

    if (typeof isShowLoading == "undefined") {
        isShowLoading = true;
    }

    if (httpMethod.toLowerCase() == "get") {
        WebUIJS.Get(url,
            data,
            function (ret) {
                __callBackFuncOrStr(onsuccess, ret, [ret]);
            },
            onError,
            function () {
                if (isShowLoading) WebUIJS.CloseLoading()
            },
            function () {
                if (isShowLoading) WebUIJS.Loading();
            });
    } else if (httpMethod.toLowerCase() == "post") {
        WebUIJS.Post(url,
            data,
            function (ret) {
                __callBackFuncOrStr(onsuccess, ret, [ret]);
            },
            onError,
            function () {
                if (isShowLoading) WebUIJS.CloseLoading()
            },
            function () {
                if (isShowLoading) WebUIJS.Loading();
            });
    }
}

function __getFormOrDivUrl(formOrDiv) {
    var that = $(formOrDiv);

    if (that.is("form")) {
        var actionUrl = that.attr("action");

        if (actionUrl && actionUrl != "") {
            return actionUrl;
        }

        if (that.closest(".modalwindow").length > 0) {
            actionUrl = that.data("url");
        } else {
            actionUrl = window.location.href;
        }

        return actionUrl;
    } else if (that.is('div[data-innerform="True"]')) {
        return that.data("url");
    }
}

function __getFormOrDivMethod(formOrDiv) {
    var that = $(formOrDiv);

    if (that.is("form")) {
        var method = that.attr("method");

        if (method && method != "") {
            return method;
        }

        if (that.closest(".modalwindow").length > 0) {
            method = that.data("method");
        } else {
            method = "get";
        }

        return method;
    } else if (that.is('div[data-innerform="True"]')) {
        return that.data("method");
    }
}

function __uploadFileToServer(file, url, options) {
    if ($(file).is("input")) {
        file = file.files[0];
    }
    else if (isArray(file) || file.length) {
        file = file[0];
    }



    var defaultOpts = {
        onProgree: null,
        onSuccess: null,
        onError: null,
        onComplete: null,
        fieldName: "file",
        'sender':null,
    }

    var opt = $.extend({}, defaultOpts, options);

    var formData = new FormData();

    if (!opt.fieldName || opt.fieldName == "") {
        opt.fieldName = "file";
    }

    // add assoc key values, this will be posts values
    formData.append(opt.fieldName, file, file.name);

    $.ajax({
        type: "POST",
        url: url,
        xhr: function () {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                if (opt.onProgree) {
                    myXhr.upload.addEventListener('progress',
                        function (e) {
                            opt.onProgree((e.loaded / e.total) * 100)
                        }, false);
                }
            }
            return myXhr;
        },
        success: function (data) {
            if (opt.onSuccess) {
                if(opt.sender && opt.sender !=null)
                {
                    opt.onSuccess.apply(opt.sender, [data]);
                }
                else{
                    opt.onSuccess(data);
                }
            }

        },
        error: function (error) {
            if (opt.onError) {
                
                opt.onError({
                    IsSuccess: false,
                    Message: error.statusText,
                    Error:error
                });
            }

        },
        complete: function () {
            if (opt.onComplete) {
                opt.onComplete();
            }
        },
        async: true,
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });
}

//修复下拉框可能被挡住的问题
$(window).on('shown.bs.dropdown', function (e) {
    if ($(e.target).is(".profile-element") || $(e.target).is(".note-btn-group")) {
        return;
    }

    if ($(e.target).is(".dropdown-treeview-buttongroup")) {
        $(e.target).closest(".dropdown-treeview-container").addClass("open");
        return;
    }

    // grab the menu        
    dropdownMenu = $(e.target).find('.dropdown-menu,.note-dropdown-menu');

    
    // detach it and append it to the body
    $('body').append(dropdownMenu.detach());

    // grab the new offset position
    var eOffset = $(e.target).offset();

    // make sure to place it where it would normally go (this could be improved)

    var dropDownMenuTop = eOffset.top + $(e.target).outerHeight();
    var dropDownMenuButtom = eOffset.top + $(dropdownMenu).outerHeight();

    //如果超出窗体高度,则向上显示
    if (dropDownMenuButtom > $(window).height() + $(window).scrollTop()) {
        dropDownMenuTop = eOffset.top - $(dropdownMenu).outerHeight() - 4;
    }

    dropdownMenu.css({
        'display': 'block',
        'top': dropDownMenuTop,
        'left': eOffset.left - 50
    });
});

// and when you hide it, reattach the drop down, and hide it normally                                                   
$(window).on('hide.bs.dropdown', function (e) {
    if ($(e.target).is(".profile-element") || $(e.target).is(".note-btn-group")) {
        return;
    }

    if ($(e.target).is(".dropdown-treeview-buttongroup")) {
        $(e.target).closest(".dropdown-treeview-container").removeClass("open");
        return;
    }

    if (dropdownMenu && dropdownMenu!=null) {
        $(e.target).append(dropdownMenu.detach());
        dropdownMenu.hide();
        dropdownMenu = null;
    }
    
});

function getTableColumnIndex(table, selector) {
    return $(table).find('thead tr th').index(table.find('thead tr').find("th" + selector));
}

function parseIntEx(value, defaultValue) {
    if (typeof defaultValue == 'undefined') {
        defaultValue = 0;
    }

    var v = parseInt(value);

    if (isNaN(v)) {
        return defaultValue;
    } else {
        return v;
    }
}

function parseDecimalEx(value, defaultValue) {

    if (typeof defaultValue == 'undefined') {
        defaultValue = new Decimal(0);
    }

    try {
        var newValue = new Decimal(value);

        return newValue;
    } catch (e) {
        return defaultValue;
    }
}

function parseFloatEx(value, defaultValue) {
    if (typeof defaultValue == 'undefined') {
        defaultValue = 0;
    }

    var v = parseFloat(value);

    if (isNaN(v)) {
        return defaultValue;
    } else {
        return v;
    }
}

function startWith(str, checkValue) {
    if (checkValue == null || checkValue == "" || str.length == 0 || checkValue.length > str.length)
        return false;
    if (str.substr(0, checkValue.length) == checkValue)
        return true;
    else
        return false;

    
}

function endWith(str, checkValue) {
    if (checkValue == null || checkValue == "" || str.length == 0 || checkValue.length > str.length)
        return false;
    if (str.substring(str.length - checkValue.length) == checkValue)
        return true;
    else
        return false;
}

function __raiseEvent(eventName, sender, args) {
    if (!sender) {
        sender = window;
    }

    var array = eventHandlers[eventName];

    if (!array || array.length <= 0) {
        return;
    }

    for (var i = 0; i < array.length; i++) {
        __callBackFuncOrStr(array[i], sender, args);
        //array[i].call(sender, args);
    }
}


//防抖处理
var debouncetimeout = null;
function debounce(fn, wait,sender,args) {
    
    var that = sender;
    return function () {
        if (debouncetimeout !== null) {
            clearTimeout(debouncetimeout);
        }
           
        debouncetimeout = setTimeout(function () {
            __callBackFuncOrStr(fn,that,args);
            debouncetimeout = null;
        }, wait);
    }
}

var debounceCallfirstStartTime = Date.now();
function debounceCallfirst(func, delay, sender) {
    debounceCallfirstStartTime = Date.now();
    var that = sender;
    
    return function () {
        var curTime = Date.now();
        var remaining = delay - (curTime - debounceCallfirstStartTime);

        if (remaining <= 0) {

            throttlestartTime = Date.now();
            return __callBackFuncOrStr(func, that, arguments);
        } else {
            return false;
        }
    }
}


//节流
var throttletimer = null;
var throttlestartTime = Date.now();
function throttle(func, delay, sender, args) {
    throttlestartTime = Date.now();
    var that = sender;
    return function () {
        var curTime = Date.now();
        var remaining = delay - (curTime - throttlestartTime);
    
        var args = arguments;
        clearTimeout(throttletimer);
        if (remaining <= 0) {
            __callBackFuncOrStr(func, that, args);
            throttlestartTime = Date.now();
        } else {
            throttletimer = setTimeout(function () {
                __callBackFuncOrStr(func, that, args);
                debouncetimeout = null;
            }, remaining);
        }
    }
}



$.htmlencode = function (s) {
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(s));
    return div.innerHTML;
}

$.htmldecode = function (s) {
    var div = document.createElement('div');
    div.innerHTML = s;
    var str = div.innerText || div.textContent;

    $(div).remove();

    return str;
}


$.getMultiScripts = function (arr, path) {
    var _arr = $.map(arr, function (scr) {
        return $.getScript((path || "") + scr);
    });

    _arr.push($.Deferred(function (deferred) {
        $(deferred.resolve);
    }));

    return $.when.apply($, _arr);
}

/**
 * 用于返回一个数组中,第一个符合selector筛选器条件的元素的索引
 * @param {*} array 
 * @param {*} selector jq的筛选器
 * @param {*} startIndex 
 */
$.indefOfElement = function (array, selector, startIndex) {
    if (!startIndex) {
        startIndex = 0;
    }

    for (var i = startIndex; i < array.length; i++) {
        if ($(array[i]).is(selector)) {
            return i;
        }
    }

    return -1;
}

$.asciiLength = function (str) {
    if (!isString(str)) {
        return 0;
    }

    var len = 0;
    for (var i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1 
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
            len++;
        }
        else {
            len += 2;
        }
    }
    return len;
    
}


function __dataPickerToConfig(data) {
    if (isArray(data)) {
        data = data[0];
    }

    var config = $.parseJSON($.htmldecode($(this).data("fillconfig")));

    WebUIJS.FillDataToControl(data, config);
}


function __callBackFuncOrStr(func, sender, args) {

    if (typeof func == "undefined") {
        return false;
    }

    if (isFunction(func)) {
        return  func.apply(sender, args);
    } else if (isString(func) && func != "") {
        try {
            if (eval("typeof(" + func + ") == typeof(Function)")) {
                return eval("window." + func).apply(sender, args);
            } else {
                return new Function("e", func).apply(sender, args);
            }

        } catch (e) {
            return new Function("e",func).apply(sender, args);
        }
        
    }
}


function _autoScaleImage(image, alignCenter) {
    if (!alignCenter) {
        alignCenter = true;
    }

    alignCenter = false;

    //image = $(image);
    var maxWidth = $(image).width();
    var maxHeight = $(image).height();

    if ($(image).attr("src")!="") {
        $(image).trigger("load");
    }

    $(image).on("load",
        function() {

            var img = new Image();
            img.src = $(image).attr("src");
            var hRatio;
            var wRatio;
            var Ratio = 1;
            var w = img.width; //图片实际宽度 
            var h = img.height;
            wRatio = maxWidth / w; //宽度缩放比 
            hRatio = maxHeight / h;
            if (maxWidth == 0 && maxHeight == 0) {
                Ratio = 1;
            } else if (maxWidth == 0) {
                if (hRatio < 1) Ratio = hRatio;
            } else if (maxHeight == 0) {
                if (wRatio < 1) Ratio = wRatio;
            } else if (wRatio < 1 || hRatio < 1) {
                Ratio = (wRatio <= hRatio ? wRatio : hRatio);
                if (wRatio < hRatio) {
                    if (alignCenter) {
                        $(image).css("marginTop", ((maxHeight - h * Ratio) / 2) + 'px'); //使图片垂直居中 
                    }
                    
                } else {
                    if (alignCenter) {
                        $(image).css("marginLeft", ((maxWidth - w * Ratio) / 2) + 'px');
                    }

                    
                    //image.style.marginLeft = (maxWidth - w * Ratio) / 2 + 'px'; //使图片水平居中 
                }
            } else {
                if (alignCenter) {
                    $(image).css("marginTop", ((maxHeight - h) / 2) + 'px'); //使图片垂直居中 
                    $(image).css("marginLeft", ((maxWidth - w) / 2) + 'px'); 
                }
                
                //image.style.marginTop = (maxHeight - h) / 2 + 'px';
                //image.style.marginLeft = (maxWidth - w) / 2 + 'px';
            }

            //if (Ratio < 1) {
            //    w = w * Ratio;
            //    h = h * Ratio;
            //}

            //$(image).height(h);
            //$(image).width(w);

            if (maxWidth == 0 && maxHeight == 0) {
                $(image).height(h);
                $(image).width(w);
            } else if (maxWidth == 0 && maxHeight != 0) {
                if (hRatio >= 1) {
                    $(image).height(h);
                    $(image).width(w);
                } else {
                    $(image).height(maxHeight);
                    $(image).width((w / h) * maxHeight);
                }
            } else if (maxWidth != 0 && maxHeight == 0) {
                if (wRatio >= 1) {
                    $(image).height(h);
                    $(image).width(w);
                } else {
                    $(image).height((h / w) * maxWidth);
                    $(image).width(maxWidth);
                }
            } else {
                if (wRatio >= 1 && hRatio >= 1) {
                    $(image).height(h);
                    $(image).width(w);
                } else if (wRatio >= 1 && hRatio < 1) {
                    $(image).height(maxHeight);
                    $(image).width((w / h) * maxHeight);
                } else if (wRatio < 1 && hRatio >= 1) {
                    $(image).height((h / w) * maxWidth);
                    $(image).width(maxWidth);
                } else {
                    if (wRatio >= hRatio) {
                        $(image).height(maxHeight);
                        $(image).width((w / h) * maxHeight);
                    } else {
                        $(image).height((h / w) * maxWidth);
                        $(image).width(maxWidth);
                    }
                }
            }
            
        });
    
}


; (function ($) {
    $.fn.hasScrollBar = function () {
        var e = this.get(0);
        return {
            vertical: e.scrollHeight > e.clientHeight,
            horizontal: e.scrollWidth > e.clientWidth
        };
    }
})(jQuery);